[英]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.