Sorting a list of dictionaries by key in Python
I have a list of dictionaries in Python, each containing only one numeric key, and I want to sort them by their keys. Example:
list = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}]
I want to sort this and return something like this:
[{1.0: 'a'}, {1.0: 'c'}, {.98: 'b'}, {.56: 'a'}]
In the case where the key values ββare the same, I don't care how they are sorted. I've tried using .sort()
or .sorted()
, but I'm having a hard time understanding the arguments.
source to share
This is a simplified version of @dkamins
>>> lst = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}]
>>> sorted(lst, key=max, reverse=True)
[{1.0: 'a'}, {1.0: 'c'}, {0.98: 'b'}, {0.56: 'a'}]
recall that it max(d.keys())
returns the same result asmax(d)
lambda d: max(d)
just wraps another function around the call max
, so we can leave that outside
source to share
This will work in Python 2 and 3:
>>> mylist = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}]
>>> sorted(mylist, key=lambda d: max(d.keys()), reverse=True)
[{1.0: 'a'}, {1.0: 'c'}, {0.98: 'b'}, {0.56: 'a'}]
It uses an argument sorted
key
to sort based on the largest key of each dict, which in this case will be the first if you only have one.
Another solution might work, but it's much easier.
PS Never name variables after Python builders are like list
.
source to share
At least in Python 3.3, @ Hai Vu's comment does not work because it throws a type error since dict () is not an ordered type. However, a comment suggests an answer if we can convert a dictionary to an ordered type, like a list of tuples:
>>>> L = [{.56: 'a'}, {1.0: 'a'}, {.98: 'b'}, {1.0: 'c'}]
>>>> L2 = sorted([list(zip(x.keys(),x.values())) for x in L],reverse=True)
>>>> L2
[[(1.0, 'c')], [(1.0, 'a')], [(0.98, 'b')], [(0.56, 'a')]]
>>>> [{k: v for (k,v) in x} for x in L2]
[{1.0: 'c'}, {1.0: 'a'}, {0.98: 'b'}, {0.56: 'a'}]
Let's start with the data assigned L
, not list
to avoid keyword confusion list
. We then use a list comprehension, which creates a list of lists of tuples, where each of the subscriptions are zipped keys and the values ββof each dictionary. They can be sorted as lists using the function sorted()
.
Unfortunately, we no longer have dictionaries, so the next step is to convert from a list of lists of tuples back to a list of dictionaries, using a dictionary comprehension within a list comprehension to convert each list of tuples to a dictionary and then return them together as a list.
source to share