简体   繁体   English

字典 python 中键的排序键

[英]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:我想我可以使用排序的 function 但我不知道如何引用“价格”键,因为它们嵌套到 Item1、Item2 等:

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.请注意,排序对于列表 object 是有意义的,但它不适用于字典,因为它们基本上是 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.因此,通过这种方式,您将拥有一个有序的元组列表(键、值),但是如果您想 go 回到字典,保留一个没有多大意义的顺序。

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给出 output 如下

[{'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'})]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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