Question

I have a form like 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}}

and i want to transform like this

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

but by using def i do not Know how to present so many values with only one def.All the necessary values are calculated but i do not know how to use them.

This is my progress until now

for key in d.keys():
    print(key)
    length=len(key)
    print(length)
    products=d[key]
    for price in products.values():
        for name,valuen in products.items():
            if valuen == price:
                print("\t",name,":",price,end="\t")
    print("\n") 
Was it helpful?

Solution

dictYou can do this also:

def get_invert_dict(dict):
  {c:{key:v} for key,value in a.iteritems() for c,v in value.iteritems()}

#Test the function
new_dict = get_invert_dict(a)
print(new_dict)

Edit: Doesn't work if multiple value for the same key (ex: persil). The last one is used as value

OTHER TIPS

This answer relies on my answer to your previous question. After getting b , the inverted dictionary, as explained in my previous answer, you can get your output with this code:

def print_data(b):
    for key, value in b.items():
        print key
        print '-' * len(key)
        for k, v in value.items():
            print ' {}: {}'.format(k, v),
        print '\n'

This gives:

cereal
------
 barakobama: 9.21

potatoes
--------
 barakobama: 2.67

parsley
-------
 vladimirputin: 1.33  barakobama: 0.76

sugar
-----
 barakobama: 1.98

crisps
------
 barakobama: 1.09

milk
----
 vladimirputin: 2.87

bread
-----
 vladimirputin: 0.66

Note that the order of food items in your expected output and my answer is not the same. This is because dictionaries are not ordered by default. You might need to explore OrderedDicts if order of elements is a concern.

Documentation on format()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top