0

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 ^

6
  • So you are asking how to sort the list of dicts by the single key of each dict? Commented May 11, 2020 at 12:09
  • yes, i want to sort based on movie @mapf Commented May 11, 2020 at 12:10
  • Are the keys of those dicts continuous ints? Commented May 11, 2020 at 12:15
  • 2
    the data structure is incorrect. Commented May 11, 2020 at 12:16
  • 1
    I think OP means [{"1": {"movie": "0.53"}}, {"2": {"movie": "5.2"}}, {"3": {"movie": "3.2"}}] Commented May 11, 2020 at 12:17

2 Answers 2

1

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'}}]
Sign up to request clarification or add additional context in comments.

Comments

0

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'}}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.