sort values and return list of keys from dict python
Question:
I have a dictionary like A = {'Name1':34, 'Name2': 12, 'Name6': 46,....}
.
How can I get a list of keys sorted by the values, i.e. [Name2, Name1, Name6....]
?
Answers:
I’d use:
items = dict.items()
items.sort(key=lambda item: (item[1], item[0]))
sorted_keys = [ item[0] for item in items ]
The key
argument to sort is a callable that returns the sort key to use. In this case, I’m returning a tuple of (value, key)
, but you could just return the value (ie, key=lambda item: item[1]
) if you’d like.
sorted(a.keys(), key=a.get)
This sorts the keys, and for each key, uses a.get
to find the value to use as its sort value.
Use sorted
‘s key
argument
sorted(d, key=d.get)
I have a dictionary like A = {'Name1':34, 'Name2': 12, 'Name6': 46,....}
.
How can I get a list of keys sorted by the values, i.e. [Name2, Name1, Name6....]
?
I’d use:
items = dict.items()
items.sort(key=lambda item: (item[1], item[0]))
sorted_keys = [ item[0] for item in items ]
The key
argument to sort is a callable that returns the sort key to use. In this case, I’m returning a tuple of (value, key)
, but you could just return the value (ie, key=lambda item: item[1]
) if you’d like.
sorted(a.keys(), key=a.get)
This sorts the keys, and for each key, uses a.get
to find the value to use as its sort value.
Use sorted
‘s key
argument
sorted(d, key=d.get)