-4

I want to take a dictionary with this form

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}}



d={}
p={}
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}} 
for key in a:
    for product in a[key]:
        price=a[key][product]
        d[key]=price
        p[product]=d
print(p)

and transform it into this

p={'milk': {'vladimirputin': 2.87}, 'cereal': {'barakobama': 9.21},'bread': {'vladimirputin': 0.66}, 'potatoes': {'barakobama': 2.67},'sugar': {'barakobama': 1.98}, 'parsley': {'vladimirputin': 1.33,'barakobama': 0.76}, 'crisps': {'barakobama': 1.09}}.
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81

2 Answers2

0

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.

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
0

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 not in 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
Zweedeend
  • 2,565
  • 2
  • 17
  • 21