简体   繁体   English

Python如何通过字典键对嵌套字典列表进行排序?

[英]Python how to sort a list of nested dictionaries by dictionary keys?

I have a list of nested dictionaries, of the form: 我有以下形式的嵌套字典列表:

list = [{key1: (tuple_value1, tuple_value2)}, {key2: (tuple_value1, tuple_value2)}, {key3: (tuple_value1, tuple_value2)}, ...]

How can I sort this list based on the KEYS in this list? 如何根据列表中的KEY对列表进行排序? I want the list to be sorted so that the keys are in alphabetical order. 我希望对列表进行排序,以便键按字母顺序排列。

I found an expression that will sort by the values I believe: 我找到了一个表达式,该表达式将按我认为的值排序:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

But I've yet to be successful sorting by the keys. 但我尚未成功按键进行排序。

you can do. 你可以做。 This will sort your dict by keys. 这将按键对字典排序。 This is work only on Python 2.7 这仅在Python 2.7上有效

newlist = sorted(list_to_be_sorted, key=lambda k: k.keys()) 

Try (works for both versions): 尝试(适用于两个版本):

>>> lod=[{'b':[1,2,3]},{'a':[4,5,6]}]
>>> sorted(lod,key=lambda x: list(x.keys()))
[{'a': [4, 5, 6]}, {'b': [1, 2, 3]}]
>>> 

Of course this would also work (works for both versions): 当然这也可以工作(两个版本均适用):

>>> lod=[{'b':[1,2,3]},{'a':[4,5,6]}]
>>> lod.sort(key=lambda x: list(x.keys()))
>>> lod
[{'a': [4, 5, 6]}, {'b': [1, 2, 3]}]
>>> 

But for python 2, @ManojJadhav's answer is the best, because it's faster, not using list outside, (this can do a pretty big change with larger dictionaries) 但是对于python 2,@ ManojJadhav的答案是最好的,因为它更快,不使用外部list ,(使用较大的字典可以做很大的改变)

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

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