[Tutor] R: Re: Create complex dictionary :p:
Steven D'Aprano
steve at pearwood.info
Tue Oct 27 18:51:21 EDT 2015
On Tue, Oct 27, 2015 at 10:37:11PM +0100, jarod_v6--- via Tutor wrote:
> Sorry,
> I just realize my question are wrong: I want to knowhow to do dictionary of
> dictionary in most python way:
>
> diz = { "A"={"e"=2,"s"=10},"B"={"e"=20,"s"=7}}
Like that, except you need to use colons:
diz = {"A": {"e": 2, "s": 10},
"B": {"e": 20, "s": 7},
"C": {"a": 1, "b": 2, "c": 3},
}
If your dictionary can be calculated, you could write this:
diz = dict((key, dict((k,v) for (k,v) in zip("es", range(2))))
for key in "ABCD")
print(diz)
=> prints this nested dict:
{'B': {'s': 1, 'e': 0}, 'A': {'s': 1, 'e': 0}, 'D': {'s': 1, 'e': 0},
'C': {'s': 1, 'e': 0}}
but that rapidly gets complicated and hard to read! A better idea might
be something like this:
innerdict = {"e": 0, "s": 1}
diz = dict((key, innerdict.copy()) for key in "ABCD")
> So I have some keys (A,B) is correlate with a new dictionary where I have
> other key I want to use. I want to extract for each key the "e" value.
> thanks
# Method one:
for key in diz:
value = diz[key]["e"]
print("The key is %s, the value is %s" % (key, value))
# Method two:
for key, subdict in diz.items():
value = subdict["e"]
print("The key is %s, the value is %s" % (key, value))
# Method three:
for subdict in diz.values():
value = subdict["e"]
print("The key is unknown, the value is %s" % value)
--
Steve
More information about the Tutor
mailing list