When I create a multi level dictionary (or JSON) I have to initialize at each level and it overwrites the old data
For example I’d like to create
dict1 = {}
for i in ["i","you"]:
for j in ["have", "has", "had"]:
for k in ["a","an"]:
for m in ["apple", "pear"]:
for n in ["cat","dog"]:
dict1[i] = {j:{k:{"fruit":m,"animal":n}}}
print(dict1)
I would like to have the result of
{'i': {'have': {'a': {'fruit': 'apple', 'animal': 'cat'}}},
'you': {'have': {'a': {'fruit': 'apple', 'animal': 'dog'}}}
and so on. However I am receiving only the last 2 permutations as they always get overwritten.
2
Answers
You are overriding the key every iteration of the inner loops. Use a
list
insteadOutput
Edit
You can keep the
dict
format if you add an additional unique keyOutput
Edit 2:
Keys in
dict
must be unique, you can’t havei
key more than once. If you don’t want to use one of the above options the only other way is to use atuple
as the key#You will still have the issue duplicate keys in the inner loops of
fruit
andanimal
(if you really need them), to get all the options you will still need a listCreating in one shot a nested structure requires a good initialization at each level.
In your approach you can adopt
defaultdict
The output is not exactly a dict, but works in the same way.