[python]defaultdict (그래프 자료구조 변환할 때)

건너별·2021년 12월 2일
0

python

목록 보기
3/12

목적

  • Graph 자료구조로부터, node 별로 이어진 다른 node들을 dictionary 형태로 변형하고 싶다.

예를 들어, 아래와 같이 edge 정보가 담겨있을때

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

{1: [3, 2], 2: [3, 1, 4, 5], 3: [6, 4, 2, 1], 4: [3, 2], 5: [2], 6: [3]}
이렇게 출력하고 싶음.

1차시도: dictionary comprehension

-> 안됨

{key:[value] for key,value in edge}

>>> {3: [2], 4: [3], 1: [2], 2: [4], 5: [2]}

2차시도: for문으로 해봤는데, 원하는 결과가 안나옴. 할수는 있는데 좀 생각이 더 필요할듯.

for key, value in edge:
    dic={}
    if not key in dic:
        dic[key]=[value]
    else:
        dic[key]+=[value]
print(dic)

>>> {5: [2]} # 이상해

defaultdict 활용!

  • default data type을 지정할 수 있는 dictionary

  • 복잡하게 if문으로 나눌 필요가 없어짐

  • dictionary value의 default type 설정 : int, list
    -> key값이 있을때 없을때 if문으로 분류할 필요 없이 간단히 코딩 가능

  • 추가적으로 sorted로 정렬할 수 있음

from collections import defaultdict

dic=defaultdict(list)
for key, value in edge:
    dic[key]+=[value]
    dic[value]+=[key]
print(dict(sorted(dic.items())))


>>>
{1: [3, 2], 2: [3, 1, 4, 5], 3: [6, 4, 2, 1], 4: [3, 2], 5: [2], 6: [3]}

😎성공!

  • defaultdict 활용하면 dictionary의 value값으로 list, int등 폭넓은 활용이 가능하다.
  • node가 숫자가 아닌 str 등의 다른 data type일때도 문제 없이 구조 변환이 가능하다.
profile
romantic ai developer

0개의 댓글