python/basic
[Python] sorted()
wjwkddyd221001
2023. 2. 11. 22:32
개요
내장함수 sorted()는 리스트, 딕셔너리를 오름차순 혹은 내림차순으로 정렬할 수 있다.
sorted()
- sorted(정렬할 데이터, key, reverse)
- Parameters
- key
- reverse
- reverse = False(기본값) # 오름차순
- reverse = True # 내림차순
- return 값 : list
예제
- dictionary의 value를 기준으로 정렬
dic = {
"c":3,
"a":1,
"b":2,
"z":26,
}
result = sorted(dic.items(), key = lambda x : x[1])
print(result) # [('a', 1), ('b', 2), ('c', 3), ('z', 26)]
print(dict(result)) # {'a': 1, 'b': 2, 'c': 3, 'z': 26}