在Python中结合列表的字典

use*_*088 20 python dictionary list

我有一个非常大的(p,q)元组集合,我想将其转换为列表字典,其中每个元组中的第一项是索引包含q的列表的键.

例:

Original List: (1, 2), (1, 3), (2, 3)  
Resultant Dictionary: {1:[2, 3], 2:[3]}  
Run Code Online (Sandbox Code Playgroud)

此外,我想有效地结合这些词典.

例:

Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}  
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}  
Run Code Online (Sandbox Code Playgroud)

这些操作位于内部循环中,所以我希望它们尽可能快.

提前致谢

Ale*_*lli 15

如果按照itertools.groupby@gnibbler的建议对元组列表进行排序,则它不是一个糟糕的替代方案defaultdict,但需要使用与他建议的不同的方式:

import itertools
import operator

def lot_to_dict(lot):
  key = operator.itemgetter(0)
  # if lot's not sorted, you also need...:
  # lot = sorted(lot, key=key)
  # NOT in-place lot.sort to avoid changing it!
  grob = itertools.groupby(lot, key)
  return dict((k, [v[1] for v in itr]) for k, itr in grob)
Run Code Online (Sandbox Code Playgroud)

用于将列表的"合并"列入新的dol ..:

def merge_dols(dol1, dol2):
  keys = set(dol1).union(dol2)
  no = []
  return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys)
Run Code Online (Sandbox Code Playgroud)

鉴于性能很重要,我给出[]了一个昵称,no以避免无用地构建大量空列表.如果dols'键的集合仅适度重叠,则更快:

def merge_dols(dol1, dol2):
  result = dict(dol1, **dol2)
  result.update((k, dol1[k] + dol2[k])
                for k in set(dol1).intersection(dol2))
  return result
Run Code Online (Sandbox Code Playgroud)

因为这仅对重叠键使用list-catenation - 所以,如果这些很少,它会更快.


Sil*_*ost 9

collections.defaultdict 像这样工作:

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

类似于 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)
Run Code Online (Sandbox Code Playgroud)