排序字典,其中包含按值列出的字典列表

时间:2019-05-23 13:06:44

标签: python list sorting dictionary

我有以下格式的字典:

{"key1": [{"title":"bla bla", "percentage": "0.3493"},{"title":"bla bla bla", "percentage":"0.293"}],
"key2": [{"title":"bla bla", "percentage": "0.635"},{"title":"bla bla bla", "percentage":"0.987"}]}

因此,基本上它是一本字典,其中包含字典列表作为值。

我想按百分比字段的降序对它进行排序-因此,对于以上示例,我想获得:

{"key1": [{"title":"bla bla", "percentage": "0.3493"},{"title":"bla bla bla", "percentage":"0.293"}],
"key2": [{"title":"bla bla bla", "percentage": "0.987"},{"title":"bla bla", "percentage":"0.635"}]}

我也想获得最高百分比的全局视图。例如:

  1. “ key2”:{“标题”:“ bla bla bla”,“百分比”:“ 0.987”}

  2. “ key2”:{“标题”:“ bla bla”,“百分比”:“ 0.635”}

  3. “ key1”:{“标题”:“ bla bla”,“百分比”:“ 0.3493”}

  4. “ key1”:{“标题”:“ bla bla bla”,“百分比”:“ 0.293”}

我研究了Python中的各种排序方式,但是我仍然不确定如何实现这一点。

1 个答案:

答案 0 :(得分:4)

我们将字典中每个键的值列表按键percentage的值降序排列,然后使用字典理解来重新创建字典

dct = {"key1": [{"title":"bla bla", "percentage": "0.3493"},{"title":"bla bla bla", "percentage":"0.293"}],
"key2": [{"title":"bla bla", "percentage": "0.635"},{"title":"bla bla bla", "percentage":"0.987"}]}

result = {key: sorted(value, key=lambda x:x['percentage'], reverse=True) for key, value in dct.items()}
print(result)

输出将为

{'key1': [{'title': 'bla bla', 'percentage': '0.3493'}, 
{'title': 'bla bla bla', 'percentage': '0.293'}], 
'key2': [{'title': 'bla bla bla', 'percentage': '0.987'}, 
{'title': 'bla bla', 'percentage': '0.635'}]}

对于全局视图,我们首先更新内部字典,以便在此处具有key属性。 然后,我们通过合并所有值列表来创建值的整体列表(全局视图),然后按降序对它们进行排序

dct = {"key1": [{"title":"bla bla", "percentage": "0.3493"},{"title":"bla bla bla", "percentage":"0.293"}],
"key2": [{"title":"bla bla", "percentage": "0.635"},{"title":"bla bla bla", "percentage":"0.987"}]}

#Update inner dictionaries with the name of the key for each dictionary
for key, value in dct.items():
    for v in value:
        v.update({'key':key})

global_view = sorted([v for value in dct.values() for v in value], key=lambda x:x['percentage'], reverse=True)

print(global_view)

这里的输出将是

[
{'title': 'bla bla bla', 'percentage': '0.987', 'key': 'key2'}, 
{'title': 'bla bla', 'percentage': '0.635', 'key': 'key2'}, 
{'title': 'bla bla', 'percentage': '0.3493', 'key': 'key1'}, 
{'title': 'bla bla bla', 'percentage': '0.293', 'key': 'key1'}
]