Doppel
Doppel

Reputation: 7

adding the values of multiple dictionarys together python

having a issue with this, not really sure what to say. it needs me to say more post this but i don't know what to say. not sure what to do.

dict1 = {'a':1,'b':2,'c':3}
dict2 = {'a':2,'b':3,'c':4}
dict3 = {'a':4,'b':3,'c':2}
dict4 = {'list1':{},'list2':{},'list3':{}}
dict4['list1'] = list1
dict4['list2'] = list2
dict4['list3'] = list3
for k,v in sorted(list4.items()):
    print (k + ":")
    for k2,v2 in sorted(v.items()):
        print ("\t" + k2 + "," + str(v2) + "\n")

it outputs like this

dict1:
    a,1

    b,2

    c,3

dict2:
    a,2

    b,3

    c,4

dict3:
    a,4

    b,3

    c,2

i want it to look like this

dict5:
    a,7

    b,8

    c,9

Upvotes: 0

Views: 45

Answers (2)

svohara
svohara

Reputation: 2189

Counter objects from the collections package are designed in part for adding dictionaries of counts together. Here's a link to a tutorial on using them.

https://pymotw.com/2/collections/counter.html

For example (with dict1..3 as defined by original post)

from collections import Counter
c1 = Counter(dict1)
c2 = Counter(dict2)
c3 = Counter(dict3)
c4 = c1 + c2 + c3
# c4 can now be accessed as a dict, and
# has the desired values

Upvotes: -1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

In python3, you can use a dictionary comprehension:

list5 = {k:sum(d[k] for d in (list1,list2,list3)) for k in ('a','b','c')}

Then it will work using the code you've already written:

print('list5:')
for k,v in sorted(list5.items()):
    print ("\t" + k + "," + str(v) + "\n")

Also, you probably shouldn't give the name "list5" to a dictionary...

Upvotes: 2

Related Questions