Combining Dictionaries Of Lists In Python

前端 未结 5 942
独厮守ぢ
独厮守ぢ 2020-11-27 19:20

I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that

5条回答
  •  粉色の甜心
    2020-11-27 19:36

    collections.defaultdict works like this:

    from collections import defaultdict
    dic = defaultdict(list)
    for i, j in tuples:
        dic[i].append(j)
    

    similar for the dicts:

    a, b = {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
    de = defaultdict(list, a)
    for i, j in b.items():
        de[i].extend(j)
    

提交回复
热议问题