I am trying to write a dictionary comprehension.
I have a dictionary like this one:
main_dict = {
'A' : {'key1' : 'valueA1', 'key2' : 'valueA2'},
'B' : {'key2' : 'valueB2', 'key3' : 'valueB3'},
'C' : {'key3' : 'valueC3', 'key1' : 'valueC1'}}
I want to perform the following logic:
d = {}
for k_outer, v_outer in main_dict.items():
for k_inner, v_inner in v_outer.items():
if k_inner in d.keys():
d[k_inner].append([k_outer, v_inner])
else:
d[k_inner] = [[k_outer, v_inner]]
Which yields the following result:
{'key3': [['C', 'valueC3'], ['B', 'valueB3']],
'key2': [['A', 'valueA2'], ['B', 'valueB2']],
'key1': [['A', 'valueA1'], ['C', 'valueC1']]}
(I know I could use defaultdict(list) but this is just an example)
I want to perform the logic using a dict-comprehension, so far I have the following:
d = {k : [m, v] for m, x in main_dict.items() for k, v in x.items()}
This does not work, it only gives me the following output:
{'key3' : ['B', 'valueB3'],
'key2' : ['B', 'valueB2'],
'key1' : ['C', 'valueC1']}
Which is the last instance found for each inner_key…
I am at a loss of how to perform this nested list-comprehension correctly. I have tried multiple variations, all worse than the last.
in the end, this is what i used: