Jwan622
Jwan622

Reputation: 11659

create nested dictionary in python dynamically

Say I have these two lists:

top_levels = ["a", "b", "c"]
sub_levels = ["d", "e", "f"]

How do I create:

nested_dict = {
   "a": {"d": 0, "e": 0, "f": 0},
   "b": {"d": 0, "e": 0, "f": 0},
   "c": {"d": 0, "e": 0, "f": 0},
}

Upvotes: 1

Views: 840

Answers (2)

Adrian
Adrian

Reputation: 11

tops =['a','b','c']
subs = ['d','e','f']
sub_dict= {i:0 for i in subs}
nested = {t:sub_dict.copy() for t in tops}
print(nested)

{'a': {'d': 0, 'e': 0, 'f': 0}, 'b': {'d': 0, 'e': 0, 'f': 0}, 'c': {'d': 0, 'e': 0, 'f': 0}}

create the subs dict and make copies of it.

Upvotes: 1

ddejohn
ddejohn

Reputation: 8960

You can use a comprehension:

>>> top_levels = ["a", "b", "c"]
>>> sub_levels = ["d", "e", "f"]
>>> {t: {s: 0 for s in sub_levels} for t in top_levels}
{'a': {'d': 0, 'e': 0, 'f': 0}, 'b': {'d': 0, 'e': 0, 'f': 0}, 'c': {'d': 0, 'e': 0, 'f': 0}}

Upvotes: 1

Related Questions