반응형
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)
반응형
'개발하자' 카테고리의 다른 글
| Python 배열/행렬 치수 (0) | 2023.01.16 |
|---|---|
| 파이썬의 매트릭스 기본 도움말 (1) | 2023.01.16 |
| MongoDB와 관련된 FastAPI 문제 - TypeError: 'ObjectId' 개체를 인식할 수 없습니다. (0) | 2023.01.15 |
| Fast API - 필드 필수, 누락된 값 (0) | 2023.01.14 |
| 사용자 지정 미들웨어 때문에 Fast API Swager가 렌더링되지 않습니까? (0) | 2023.01.14 |