So I’m wondering if anyone can help me out with this issue I’m having.
Lets assume I have a dictionary:
d = {1: {2: 3}, 4: 5}
I want to create a dictionary of any contained dictionaries:
wanted_result = {2: 3}
what I am trying is this:
e = {inner_key: d[key][inner_key] for key in d.keys() for inner_key in d[key].keys() if isinstance(d[key], dict)}
However this is causing me to get an error saying that ints don’t have keys, which I know, but I thought my conditional would exclude say 4 from my example from being included in the comprehension.
My first idea was something like this:
But, in order to avoid letting
sum()construct a large temporary list of all theitems()you may use itertools.chain anditeritems()instead:You should be aware of edge cases. Especially if identical keys are in the part-dictionaries these will necessarily collapse somehow.
If you also want to support subclasses of
dictto be collected from yourd.values(), you may indeed want to useisinstanceinstead oftype. See this question for details.