1

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},
}

2 Answers 2

1

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}}
Sign up to request clarification or add additional context in comments.

5 Comments

This answer is incorrect. It creates three references to the same dictionary. Try modifying one of the dictionaries: d['a']['d']=10 - and see when happens to the other two. The list/dict comprehension solution is correct.
Good catch. Fixed.
Now I'm sitting here thinking "wtf is the point of 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?
@blorgon: It's dramatically faster for the cases where it can be used. Among other things, back before 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.
Right, that was actually the first iteration of my solution in REPL, but at that point it seems silly to not just resort back to a pure comprehension version. I'd be curious about the performance for larger sequences but am too lazy to do any testing.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.