【问题标题】:How can I concatenate dicts (values to values of the same key and new key)? [duplicate]如何连接 dicts(值到相同键和新键的值)? [复制]
【发布时间】:2017-04-24 06:02:57
【问题描述】:

我在连接字典时遇到问题。有这么多代码,所以我在示例中显示我的问题是什么。

d1 = {'the':3, 'fine':4, 'word':2}
+
d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
+
d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}
=
finald = {'the':10, 'fine':16, 'word':6, 'knight':1, 'orange':1, 'sequel':1, 'jimbo':1}

它正在为 wordcloud 准备字数。我不知道如何连接键的值,这对我来说很困惑。请帮忙。 最好的问候

【问题讨论】:

标签: python dictionary word-cloud textedit


【解决方案1】:

为此,我会使用来自collectionsCounter

from collections import Counter

d1 = {'the':3, 'fine':4, 'word':2}
d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}

c = Counter()
for d in (d1, d2, d3):
    c.update(d)
print(c)

输出:

Counter({'fine': 16, 'the': 10, 'word': 6, 'orange': 1, 'jimbo': 1, 'sequel': 1, 'knight': 1})

【讨论】:

  • Counters 最近似乎解决了很多 dict 问题!对于这个问题,我会做 reduce(lambda x,y:Counter(x)+Counter(y),[d1,d2, d3]) 。 update() 比添加计数器更快/更好吗?
  • @themistoklik 可能不会太多,如果有的话,reduce 在 python 3 中已被弃用。我最初是用 map(c.update, (d1, d2, d3)) 编写的,但后来我的内部函数式程序员拒绝让我像这样滥用副作用。
【解决方案2】:
import itertools

d1 = {'the':3, 'fine':4, 'word':2}
d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}
dicts = [d1, d2, d3]

In [31]: answer = {k:sum(d[k] if k in d else 0 for d in dicts) for k in itertools.chain.from_iterable(dicts)}

In [32]: answer
Out[32]: 
{'sequel': 1,
 'the': 10,
 'fine': 16,
 'jimbo': 1,
 'word': 6,
 'orange': 1,
 'knight': 1}

【讨论】:

  • 'knight'、'sequel'、'orange' 和 'jimbo' 呢?
  • @InspectorGadget 干得好!
  • 天哪,谢谢漂亮的 oneliner :)
  • 为什么投反对票?
【解决方案3】:
def sumDicts(*dicts):
    summed = {}
    for subdict in dicts:
        for (key, value) in subdict.items():
            summed[key] = summed.get(key, 0) + value
    return summed

外壳示例:

>>> d1 = {'the':3, 'fine':4, 'word':2}
>>> d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
>>> d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}
>>> sumDicts(d1, d2, d3)
{'orange': 1, 'the': 10, 'fine': 16, 'jimbo': 1, 'word': 6, 'knight': 1, 'sequel': 1}

【讨论】:

  • if key in summed... 可能会更好summed[key] = summed.get(key, 0) + value
  • @SeanMcSomething 在我的计算机上不起作用...说“无法分配给函数调用”
  • 抱歉,有些事情搞混了。已在编辑中修复。
  • @SeanMcSomething 已修复!
猜你喜欢
  • 2014-11-21
  • 1970-01-01
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 2018-01-04
  • 2014-08-19
  • 2015-09-22
相关资源
最近更新 更多