[英]How to sort python dictionary by value and key
I want to ort the dict by key and value我想通过键和值来破坏字典
d = {'i': 1, 'live': 2, 'in': 2, 'bangalore': 2, 'is': 1, 'good': 1, 'city': 1, 'to': 1}
output will be output 将
{'bangalore': 2, 'in': 2, 'live': 2, 'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1}
The linked question's answer can be adapted to your question:链接问题的答案可以适应您的问题:
d = {k: v for k, v in sorted(d.items(), key = lambda x: (-x[1], x[0]))}
For your example对于你的例子
d = {'i': 1, 'live': 2, 'in': 2, 'bangalore': 2, 'is': 1, 'good': 1, 'city': 1, 'to': 1}
d = {k: v for k, v in sorted(d.items(), key = lambda x: (-x[1], x[0]))}
print(d)
we get我们得到
{'bangalore': 2, 'in': 2, 'live': 2, 'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1}
as requested.按照要求。
sorting by key, then value is a simple sort operation on items:按 key 排序,然后 value 是对项目的简单排序操作:
d = dict(sorted(d.items()))
print(d)
{'bangalore': 2, 'city': 1, 'good': 1, 'i': 1, 'in': 2,
'is': 1, 'live': 2, 'to': 1}
To sort first on value then key, you can use the reversed tuples from the dictionary's items()
as your sort key:要先按值排序,然后按键排序,您可以使用字典
items()
中的反转元组作为排序键:
d = dict(sorted(d.items(),key=lambda kv:kv[::-1]))
print(d)
{'city': 1, 'good': 1, 'i': 1, 'is': 1, 'to': 1,
'bangalore': 2, 'in': 2, 'live': 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.