[英]Sort python dictionary base length of values as list
我有一个 python 字典,其值为整数列表。 我想根据列表值的长度按降序对其进行排序
_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]
}
输出应该像
_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.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)}
这是根据值对字典进行排序的单行器。 键是 x[0]('owner_1'、'owner_2' 等),值是 x[1] 的长度或与键对应的列表中的项目数。 最后 reverse= True 以相反的顺序打印字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.