简体   繁体   English

如何按列表的值对字典列表进行排序?

[英]How do I sort a list of dictionaries by a value of the list?

aa = ['a', 'b', 'c', 'd']
bb = [{'b':1, 'c':0, 'd':2, 'a':5}, {'b':5, 'c':6, 'd':1, 'a':2}]

I want to arrange the dicts in bb list by aa list.我想通过 aa 列表排列 bb 列表中的字典。

bb = [{'a':5, 'b':1, 'c':0, 'd':2}, {'a':2, 'b':5, 'c':6, 'd':1}]

You can use list- and dict-comprehensions:您可以使用列表和字典理解:

aa = ['a', 'b', 'c', 'd']
bb = [{'b':1, 'c':0, 'd':2, 'a':5}, {'b':5, 'c':6, 'd':1, 'a':2}]

output = [{k: dct[k] for k in aa} for dct in bb]
print(output)
# [{'a': 5, 'b': 1, 'c': 0, 'd': 2}, {'a': 2, 'b': 5, 'c': 6, 'd': 1}]

This "sorting" is guaranteed since python 3.7.这种“排序”自 python 3.7 以来得到保证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM