2016-12-08 4 views
0

辞書を連結する際に問題があります。あまりにも多くのコードを持っているので、私の問題点を例で示します。dicts(値を同じキーと新しいキーの値に連結するにはどうすればよいですか?)

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} 

これは、ワードクラウドに必要な単語数です。私はそれが私のためのパズルであるキーの値を連結する方法を知らない。助けてください。 敬具

+1

は[そう]へようこそ! [ask]を確認して、試したことをお見せしてください! – TemporalWolf

答えて

5

私はこのためにcollectionsからCounterを使用します。

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}) 
+0

カウンターは最近、多くのディクテーションの問題を解決するようです!この問題について私は 'reduce(lambda x、y:Counter(x)+ Counter(y)、[d1、d2、d3])'を実行します。 update()はカウンターを追加するよりも速く/良いのですか? – themistoklik

+0

@themistoklikおそらく多くの場合ではないでしょうし、python 3では 'reduce'が非難されています。私はもともと' 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} 
+0

「ナイト」「続編」「オレンジ」「ジンボ」はどうですか? – rassar

+0

@InspectorGadgetはうまくいった! – rassar

+0

omgありがとうoneliner :) – MTG

2
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} 
+0

もし 'key in summed ...'がおそらく 'summed [key] = summed.get(key、0)+ value'として良いでしょう。 –

+0

@SeanMc私のコンピュータでは動作しません。関数呼び出しに割り当てる " – rassar

+0

申し訳ありませんが、いくつかのものが混ざっています。編集時に修正されました。 –

関連する問題