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},
}
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}}
d['a']['d']=10 - and see when happens to the other two. The list/dict comprehension solution is correct.fromkeys()?" I never actually use it but it was the first thing I thought of trying when I read the OP. Now I'm actually wondering, what is its use-case?set existed, and now, when dict can be used to make a set-like thing that maintains insertion order, it's a quick drop in replacement for the set constructor. And it's perfectly safe whenever the values aren't used, or are immutable types like int. In your code, you could safely do {t: dict.fromkeys(sub_levels, 0) for t in top_levels}, you just can't use it for the outer dict due to aliasing.