简体   繁体   中英

Sort key of key in dictionary python

I have a dictionary which has some dictionaries inside. Like this:

Dict= {
"Item1": {"price": 73814.55, "date": f_actual}, 
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}

I want to sort the attribute 'price' (from highest to lowest). I think I can use sorted function but I dont know how to refer to ´price´ key since they are nested to Item1, Item2, etc:

sorted(Dict, key = ??, reverse = True)

So, my question is how can I do this? Is there any other approach?

I would do it this way:

sorted(Dict.items(), key=lambda x: x[1].get('price'), reverse=True)

Please note that ordering makes sense for lists object, but it doesn't for dictionaries, since they are basically HashMaps.

So in this way you will have an ordered list of tuples (key, value), but if you want to go back to a dictionary preserving an order that doesn't make much sense.

Please also give a look at this answer here: How do I sort a dictionary by value?

I am sure there is an elegant way. Just wait for somebody to give a cleaner/faster solution. In the meanwhile...

print([Dict[i] for i in sorted(Dict, key=lambda item: Dict[item]["price"], reverse=True)])

Gives the output as below

[{'price': 84200, 'date': 'f2'}, {'price': 75700, 'date': 'f1'}, {'price': 73814.55, 'date': 'f_actual'}]

This will do the trick for you

Dict= {
"Item1": {"price": 73814.55, "date": f_actual}, 
"Item2": {"price": 75700, "date": f1},
"Item3": {"price": 84200, "date": f2}
}

print(sorted(Dict.items(), key=lambda x: x[1]["price"], reverse=True))

[('Item3', {'price': 84200, 'date': 'f2'}), ('Item2', {'price': 75700, 'date': 'f1'}), ('Item1', {'price': 73814.55, 'date': 'f_actual'})]

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