I have a dictionary of dictionaries:
my_dict = {
'a': {(1,2): True,
(1,3): False},
'b': {(1,4): True,
(2,3): False}
}
The dictionary is always of this form, but every 'child' dictionary has a different set of keys: my_dict['a'][(1,2)]
exists, but that doesn't mean my_dict['b'][(1,2)]
also exists.
I want a list (in no particular order) of the boolean values:
[True, False, True, False]
I am trying to use a single list comprehension to accomplish this:
[my_dict[letter][pair] for pair in my_dict[letter] for letter in my_dict]
This raises an error:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-142-dc1565efcdc8> in <module>()
6 }
7
----> 8 [my_dict[letter][pair] for pair in my_dict[letter] for letter in my_dict]
KeyError: (2, 3)
It appears to be looking for (2,3) in both my_dict['a'] and my_dict['b']. I thought the comprehension I wrote would only look for the keys in the appropriate dictionary.
I've seen this solution which can work to flatten any nested dictionary. I also know I could brute force it with imperative loops. I am just trying to understand why the list comprehension isn't working the way I have it written.