1
votes

I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{'A': 25 , 'B': 41, 'C': 32}

and dict2

{'D':21, 'A': 12, 'B':62}

I'm writing a program where I need to add the values associated with the same key. So like this:

{'A': [25 + 12], 'B': [41 + 62], 'C': [32], 'D': [21]}
3
What's your question? Just loop over the keys of one of the dicts, and add the corresponding elements of both dicts. - Barmar

3 Answers

0
votes

I am going to assume you are working to preserve dict_1 as the result

for key in dict_1:
    if key in dict_2:
        dict_1[key] = dict_1[key] + dict_2[key]

Need to copy key-value pairs that exist in 2 but not in 1

for key in dict_2:
    if key not in dict_1:
        dict_1[key] = dict_2[key]

Is probably the simplest way to do this

0
votes
>>> dict1= {'A':25,'B':41,'C':32}
>>> dict2= {'D':21, 'A':12, 'B':62}
>>> for e in dict2:
        if e in dict1:
            dict1[e]=dict1[e]+dict2[e]
        else:
            dict1[e]=dict2[e]

Now your dict1 becomes the answer you want. Hope that helps. :)

0
votes

I think what you're missing in your solution is the use of the keys-method and the get-method that comes with dictionaries. The keys-method will return a list of all of keys in the key-value pairs from your dictionary. Whereas, the get-method will return the value associated with a key in the dictionary, if it's there, or return a default (defaults to None).

To do what you're trying to do, I'd recommend something like this:

x = {'a': 1, 'b': 1, 'c': 1}              # dictionary x
y = {'c': 1, 'd': 1, 'e': 1}              # dictionary y
z = dict([
    (key, x.get(key, 0) + y.get(key, 0))  # key, sum(x,y)
    for key in                            # for every key in
    set(x.keys() + y.keys())              # the unique set of keys from x + y
])

Step #1: set(x.keys() + y.keys()) - add the two lists of keys together and removes the duplicates (by making it a set)

Step #2: for key in - loop over every key in the set from Step #1

Step #3: x.get(key, 0) + y.get(key, 0) - sum the values associated with that key from each of the dictionaries; using 0 as a default if there is no associated value

Step #4: (key, ...) - create a key, value pair using the new sum and the original key

Step #5: dict([...]) - create a new dictionary from the list of key-value pairs


Does that make sense? I hope that helps!