greenhelix
greenhelix
greenhelix
05-09 06:46
  • All (229)
    • Algorithm (118)
      • Algorithm (17)
      • Graph (0)
      • Core (6)
      • Python (18)
      • PythonSnippet (4)
      • Java (59)
      • Kotlin (14)
    • Project (0)
    • Study (8)
      • License (5)
      • EIP (3)
    • Programming (63)
      • Android (41)
      • Flutter (1)
      • Bugs Life (21)
      • Linux (0)
    • Tech (32)
      • Tech (17)
      • Drone (4)
      • Hacking (11)
    • Life (6)
      • INGRESS (1)
      • 심시티빌드잇 (0)
250x250

티스토리

hELLO · Designed By 정상우.
greenhelix

greenhelix

Defaultdict, dict  sort  딕셔너리 정렬방법
Algorithm/PythonSnippet

Defaultdict, dict sort 딕셔너리 정렬방법

2021. 5. 6. 10:46

sorted(dict) 을 하게 되면 해당 딕셔너리의 키값들만 가져와서 정렬해준다.

test = {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}

print(test)
print(sorted(test))
print(sorted(test.items()))
print(dict(sorted(test.items())))

>>> {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
>>> ['blue', 'red', 'yellow']
>>> [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> {'blue': [2, 4], 'red': [1], 'yellow': [1, 3]}

키를 기준으로 딕셔너리를 정렬하고 출력은 그대로 dict형태로 가져오려면, 

sorted() 메서드를 통해서 list(tuple)형태로 먼저 정렬이 된다. 

이후 dict() 메서드를 통해서 변형시켜주면 된다.

 

#value값을 기준으로 정렬해서 리스트에 넣기.
print(dictA)	#defaultdict(<class 'int'>, {1: 2, 4: 2, 5: 1, 7: 1, 3: 2, 6: 1, 2: 1})

list_of_dictA = sorted(dictA.items(), key=operator.itemgetter(1))
#key=operator.itemgetter(1)의 뜻은 정렬하고자 하는 키 값을 1번째 인덱스를 기준으로 하겠다는 뜻
#1번째 인덱스란 즉 value를 뜻함.

print(list_of_dictA)	#[(5, 1), (7, 1), (6, 1), (2, 1), (1, 2), (4, 2), (3, 2)]

#다시 딕셔너리로 바꾸기.
dictA = dict(list_of_dictA)
print(dictA)	#{5: 1, 7: 1, 6: 1, 2: 1, 1: 2, 4: 2, 3: 2}
728x90
반응형
저작자표시 비영리 변경금지

'Algorithm > PythonSnippet' 카테고리의 다른 글

Dict(Dict()) 표현  (0) 2021.05.16
합집합, 교집합, 차집합, 대칭 차집합 표현하기  (0) 2021.05.11
How to list in dict ? 리스트를 딕셔너리로  (0) 2021.05.06
    'Algorithm/PythonSnippet' 카테고리의 다른 글
    • Dict(Dict()) 표현
    • 합집합, 교집합, 차집합, 대칭 차집합 표현하기
    • How to list in dict ? 리스트를 딕셔너리로
    greenhelix
    greenhelix
    개발에 관한 것들과 개인적인 것을 담는 블로그

    티스토리툴바