예를 들어, 아래와 같이 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]}
이렇게 출력하고 싶음.
-> 안됨
{key:[value] for key,value in edge}
>>> {3: [2], 4: [3], 1: [2], 2: [4], 5: [2]}
for key, value in edge:
dic={}
if not key in dic:
dic[key]=[value]
else:
dic[key]+=[value]
print(dic)
>>> {5: [2]} # 이상해
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]}