简体   繁体   中英

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". 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. 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. There is a build in sort method on list which sort the list in-place.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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