Search code examples
pythondictionaryword-cloudtextedit

How can I concatenate dicts (values to values of the same key and new key)?


I have a problem with concatenating dictionaries. Have so much code so I show in example what my problem is.

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}

It is prepering wordcounts for wordcloud. I dont know how to concatenate values of the keys it is puzzle for me. Please help. Best regards


Solution

  • I would use a Counter from collections for this.

    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)
    

    Outputs:

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