Take Elements Of Dictionary To Create Another Dictionary
Solution 1:
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 = {}
forprezin a:
forfoodin 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.
Solution 2:
Based on the answer above, I think it it is somewhat clearer to use the items() method when iteration through a dictionary. It is more beautiful and it is even faster!
by_president = {'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}}
by_item = {}
for president, inventory in by_president.items():
for food, price in inventory.items():
if food notin by_item: # Create the inner dictionary if it didn't already exist
by_item[food] = dict()
food_dictionary = by_item[food] # A reference to the inner dictionary
food_dictionary[president] = price # Assign to the inner dictionary
Post a Comment for "Take Elements Of Dictionary To Create Another Dictionary"