在 Python 中组合列表字典

新手上路,请多包涵

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

例子:

 Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}

此外,我想有效地组合这些词典。

例子:

 Original Dictionaries: {1:[2, 3], 2:[3]}, {1:[4], 3:[1]}
Resultant Dictionary: {1:[2, 3, 4], 2:[3], 3:[1]}

这些操作驻留在一个内部循环中,所以我希望它们尽可能快。

提前致谢

原文由 user108088 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 388
2 个回答

如果元组列表已排序, 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)

对于将列表的字典“合并”到一个新的 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)

我给 [] 昵称 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

因为这只对重叠的键使用列表连接——所以,如果这些键很少,它会更快。

原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 2.5 许可协议

collections.defaultdict 像这样工作:

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

类似的字典:

 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)

原文由 SilentGhost 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题