[英]Sort python dictionary base length of values as list
I have a python dictionary with values as list of integers.我有一个 python 字典,其值为整数列表。 I want to sort it in descending order based on the length of the values which is list
我想根据列表值的长度按降序对其进行排序
_dict = {
'owner_1': [320, 203, 123, 32, 923, 12398],
'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93,
9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83],
'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912,
9219, 239, 9021092, 9294]
}
The output should be like输出应该像
_dict = {
'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93,
9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83],
'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912,
9219, 239, 9021092, 9294],
'owner_1': [320, 203, 123, 32, 923, 12398]
}
You can use sorted
on dict.items()
and use len
for value
of dict
.您可以在
dict.items()
上使用sorted
并使用len
作为dict
的value
。
>>> dict(sorted(_dict.items(), key=lambda x: len(x[1]), reverse=True))
# --------------------------------------x[0] is key, x[1] is value of each item dict
{
'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83],
'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 9219, 239, 9021092, 9294],
'owner_1': [320, 203, 123, 32, 923, 12398]
}
_dict = {
'owner_1': [320, 203, 123, 32, 923, 12398],
'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93,
9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83],
'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912,
9219, 239, 9021092, 9294]
}
sorted_dict = {}
for k in sorted(_dict, key=lambda k: len(_dict[k]), reverse=True):
sorted_dict[k] = _dict[k]
print(sorted_dict)
使用 short() 函数来解决这个问题
_dict = {
'owner_1': [320, 203, 123, 32, 923, 12398],
'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93,
9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83],
'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912,
9219, 239, 9021092, 9294]
}
{key:value for key,value in sorted(_dict.items(), key = lambda x: len(x[1]), reverse=True)}
This is a one-liner to sort your dictionary according to the values.这是根据值对字典进行排序的单行器。 Key is x[0] ('owner_1', 'owner_2' etc) and the value is the length of x[1] or the number of items in the list corresponding to the key.
键是 x[0]('owner_1'、'owner_2' 等),值是 x[1] 的长度或与键对应的列表中的项目数。 Finally reverse= True prints the dictionary in reverse order.
最后 reverse= True 以相反的顺序打印字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.