简体   繁体   中英

For a dictionary inside another dictionary how do you sort it by the value and compare different items within the dictionary

I am trying to create a function that applies a promotion to a basket (like a supermarket), each item in the basket has a group number so certain items can have the promotion applied say for example my basket dictionary is:

basket = { 
'10015' : {
        'name' : 'Diced Beef 400G',
        'price' : 4.50,
        'unit' : 'pieces', 
        'promotion' : 'get4pay3',
        'group' : 4,
        'amount' : 5,
 },
 '10017' : {
        'name' : 'Brisket Beef 400G',
        'price' : 3.50,
        'unit' : 'pieces', 
        'promotion' : 'get4pay3',
        'group' : 4,
        'amount' : 3,
 },
...
}

How do you compare each item in the dictionary ie another item might have a different group number for the promotion. And how do you sort the dictionary by price? so the promotion is applied to the cheapest item.

currently I have

amount = 0
for ident in basket:
if basket[ident]['group']==4:
    amount = amount + basket[ident]['amount']

amountPayable = amount - amount//4

Thanks

You could have written the original code with generator expression that returns all the products where group == 4 :

sum(v['amount'] for v in basket.values() if v['group'] == 4) # 8

As comments mentioned dictionaries aren't ordered so you can't sort them. That said you can sort the values in the dictionary to a list:

s = sorted(basket.values(), key=lambda x: x['price'])
s[0] # {'group': 4, 'name': 'Brisket Beef 400G', 'price': 3.5, 'amount': 3, 'promotion': 'get4pay3', 'unit': 'pieces'}

Note that if you just need the cheapest product you don't have to sort the values:

min(basket.values(), key=lambda x: x['price']) # {'group': 4, 'name': 'Brisket Beef 400G', 'price': 3.5, 'amount': 3, 'promotion': 'get4pay3', 'unit': 'pieces'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM