简体   繁体   English

如何对字典中的字典列表进行排序并在 python 中覆盖它

[英]How to sort a list of dictionaries in a dictionary and overwrite it in python

I have dictionary which contains list of dictionaries:我有字典,其中包含字典列表:

example = {
"first": [
 {"a": 1, "b": 2},
 {"a": 0, "x": 5}
],
"second": [
{"a": 5, "b": 2},
{"a": 2, "x": 5}
]
}

I want to sort lists "first" & "second" based on values of key "a".我想根据键“a”的值对列表“第一”和“第二”进行排序。 Desired outcome would be:期望的结果是:

desired = {
"first": [
 {"a": 0, "x": 5},
 {"a": 1, "b": 2}
],
"second": [
{"a": 2, "x": 5},
{"a": 5, "b": 2}
]
}

Now, I dont want to create whole new dictionary.现在,我不想创建全新的字典。 Just update lists "first" & "second" in "example" dict.只需更新“示例”字典中的“第一”和“第二”列表。 What I tried:我尝试了什么:

from operator import itemgetter

for k, v in example.items():
    v = sorted(v, key=itemgetter('a'))

That has no effect in my example dictionary.这对我的示例字典没有影响。 However it works for a single list, eg:但是它适用于单个列表,例如:

x = [{"a": 1, "b": 2},
    {"a": 0, "x": 5}
]
z = sorted(x, key = itemgetter('a'))
>>> print(z)
[{'a': 0, 'x': 5}, {'a': 1, 'b': 2}]

This is because when you assign the sorted list, you are just making the 'label' v point to the sorted list, not writing it to the dictionary.这是因为当您分配排序列表时,您只是使“标签” v指向排序列表,而不是将其写入字典。 See below, that code should do what you want.见下文,该代码应该做你想做的事。

for k, v in example.items():
    example[k] = sorted(v, key=itemgetter('a'))

sorted returns a new sorted list. sorted返回一个新的排序列表。 There is a build in sort method on list which sort the list in-place.列表上有一个内置sort方法,可以对列表进行就地排序。

for v in example.values():
    v.sort(key=itemgetter('a'))

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

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