greenhelix
greenhelix
greenhelix
06-05 14:39
  • 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

How to list in dict ?  리스트를 딕셔너리로
Algorithm/PythonSnippet

How to list in dict ? 리스트를 딕셔너리로

2021. 5. 6. 10:32

How to list in dict ?

리스트를 딕셔너리로 만들기 

 

Defaultdict

class collections.defaultdict([default_factory[, ...]])

  • default_factory : defaultdict()에서 ()안에 있는 형태를 의미한다.
    list, int, set 등 딕셔너리에 값으로 넣고 싶은 형을 선택하여 선언하면 된다. 
  • 순서가 없다.  👉 정렬하는 방법?

💰 List(list) 👉 dict(list)

#먼저 defaultdict 가 있어야 한다. 
from collections import defaultdict

sample1 = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]

# defaultdict의 default_factory를 list형으로 설정한다.
graph = defaultdict(list) 

for node1, node2 in sample1:
	graph[node1].append(node2)
    graph[node2].append(node1)

print(graph)
>>> defaultdict(<class 'list'>, {1: [2, 3], 2: [1, 4, 3, 5], 3: [1, 2, 6, 4], 4: [2, 3], 6: [3], 5: [2]}) 

 

💰 List(tuple) 👉 dict(list) 

sample2 = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

d = defaultdict(list)

for k, v in sample2:
    d[k].append(v)

print(d)
>>> defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})

 

💰 List(tuple) 👉  dict(set)

sample3 = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]

setDict = defaultdict(set)

for k, v in sample3:
    setDict[k].add(v)

print(setDict)
>>> defaultdict(<class 'set'>, {'red': {1, 3}, 'blue': {2, 4}})

 

🍐String 👉 dict(int)  :: String에서 문자들의 Count 효과를 낼 수 있다. 

sample4 = 'mississippi'

int_dict = defaultdict(int)

for k in sample4:
    int_dict[k] += 1

print(int_dict)
>>> defaultdict(<class 'int'>, {'m': 1, 'i': 4, 's': 4, 'p': 2})

 

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

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

Dict(Dict()) 표현  (0) 2021.05.16
합집합, 교집합, 차집합, 대칭 차집합 표현하기  (0) 2021.05.11
Defaultdict, dict sort 딕셔너리 정렬방법  (0) 2021.05.06
    'Algorithm/PythonSnippet' 카테고리의 다른 글
    • Dict(Dict()) 표현
    • 합집합, 교집합, 차집합, 대칭 차집합 표현하기
    • Defaultdict, dict sort 딕셔너리 정렬방법
    greenhelix
    greenhelix
    개발에 관한 것들과 개인적인 것을 담는 블로그

    티스토리툴바