개발하자

sort values and return list of keys from dict python

Cuire 2023. 1. 15. 15:42
반응형

sort values and return list of keys from dict python

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....]?




Use sorted with the get method as a key (dictionary keys can be accessed by iterating):

sorted(A, key=A.get)



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)

반응형