简体   繁体   中英

Pythonic way to sort a nested list with keys

I have a list as follows:

[{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

And I know how to do t = sorted(new_list, key=lambda i: float(i['1']['movie']), reverse=True)

but I am unsure on how can i also have the 1 , 2 , 3 as iteration ^

What you could do is convert the inner dictionaries to a list from dict.values() , select the first value, then access the "movie" key. Then pass this as a float to the key function of sorted :

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = sorted(l, key=lambda x: float(list(x.values())[0]["movie"]))

print(result)

Another option is to convert your list of dicts to a list of lists, sort the result from the resulting list dict.items() , then convert the result back to a list of dicts:

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = [
    dict(l)
    for l in sorted((list(d.items()) for d in l), key=lambda x: float(x[0][1]["movie"]))
]

print(result)

Which can also just use a basic dict.update approach to convert the list of dicts to a nested dict before sorting:

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

dicts = {}
for d in l:
    dicts.update(d)
# {'1': {'movie': '0.53'}, '2': {'movie': '5.2'}, '3': {'movie': '3.2'}}

result = [{k: v} for k, v in sorted(dicts.items(), key=lambda x: float(x[1]["movie"]))]

print(result)

Or if we want to do it in one line, we can make use of collections.ChainMap :

from collections import ChainMap

l = [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}]

result = [
    {k: v} for k, v in sorted(ChainMap(*l).items(), key=lambda x: float(x[1]["movie"]))
]

print(result)

Output:

[{'1': {'movie': '0.53'}}, {'3': {'movie': '3.2'}}, {'2': {'movie': '5.2'}}]

Btw the list that you have posted is incorrect in syntax, assuming it to be list of dictionaries. You can sort it like following:

new_list = [
    {"1":{"movie": "0.53"}},
    {"2":{"movie": "5.2"}}, 
    {"3":{"movie": "3.2"}}
    ]

t = sorted(new_list, key=lambda x: float(list(x.items())[0][1]['movie']))

Output:

[{'1': {'movie': '0.53'}}, {'3': {'movie': '3.2'}}, {'2': {'movie': '5.2'}}]

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