You could do this:
a = {'vladimirputin': {'milk': 2.87, 'parsley': 1.33, 'bread': 0.66}, 'barakobama':{'parsley': 0.76, 'sugar': 1.98, 'crisps': 1.09, 'potatoes': 2.67, 'cereal': 9.21}}
b = {}
for prez in a:
for food in a[prez]:
if food not in b:
b[food] = {prez: a[prez][food]}
else:
b[food][prez] = a[prez][food]
This gives:
{'bread': {'vladimirputin': 0.66},
'cereal': {'barakobama': 9.21},
'crisps': {'barakobama': 1.09},
'milk': {'vladimirputin': 2.87},
'parsley': {'barakobama': 0.76, 'vladimirputin': 1.33},
'potatoes': {'barakobama': 2.67},
'sugar': {'barakobama': 1.98}}
Explanation:
Your input dictionary a
has president names as keys. The output dictionary needs food items as keys.
The statement if food not in b
checks if a particular food item is already a key in the output dictionary. If it is not, it will create a new dictionary as the value. Like in the case of 'sugar': {'barakobama': 1.98}
If the key is already present in the output dictionary, it gets it and adds another key value pair to it
like in the case of 'parsley': {'barakobama': 0.76, 'vladimirputin': 1.33}
You can find out how to code progresses by adding print statements in the code and checking the value of the output dictionary b
at each step.
2
solved take elements of dictionary to create another dictionary