-1

I am trying to handle values from two different dictionaries in Python. What I need to do is operate with values which have the same key in both dictionaries.

For instance, if dictionaries are:

d1 = {1:30, 2:20, 3:30, 5:80} 
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}

I need to add values from keys 1, 2 and 3 from each dictionary.

I am trying to make an iterable of values, but, when I try to extend an empty iterable with values with a line such as:

sameKeys.extend(d1[i]))

I get an Error Key. I have tried many differents syntax but none has worked.

Jed Fox
  • 2,979
  • 5
  • 28
  • 38
AnaE
  • 3
  • 1
  • 1
    What exactly is `sameKeys`? – Christian Dean Oct 04 '16 at 17:39
  • 1
    Edit your question and make your intent clearer, `sameKeys` is what? What should it contain? What have you attempted thus far? – Dimitris Fasarakis Hilliard Oct 04 '16 at 17:44
  • Do you add them in a new dict? to the first one? or just print out the result? – Wissam Youssef Oct 04 '16 at 17:52
  • 3
    I presume you are trying to do this http://stackoverflow.com/questions/39805266/intersection-and-difference-of-two-dictionaries/39805600#39805600 – Padraic Cunningham Oct 04 '16 at 17:54
  • Thank you for all of you that replied and pointed me to a similar question. I am sorry for duplicating a question. I have searched several times before asking, but could not find any similar problem as mine, because I was stuck in the error Key. I had an idea of what I wanted to do, but could not find out why it was not working. This is my first time coding ever, so forgive me for any inconvenience – AnaE Oct 04 '16 at 20:16

3 Answers3

1

You can try like this,

for i,j in zip(d1.items(),d2.items()):
    if i[0] == j[0]:
        print i[1]+j[1]

Result

70
70
90
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
1

Iterate over any of the dict. Check whether key exists in second list. If it exists, make an entry into new dict. Below is the sample example:

>>> d1 = {1:30, 2:20, 3:30, 5:80}
>>> d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
>>> d3 = {}
>>> for key, value in d1.items():
...     if key in d2:
...         d3[key] = value + d2[key]
...
>>> d3
{1: 70, 2: 70, 3: 90}
>>>
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Here is one option:

d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}

dlist = [d1, d2]


# As a dict comprehension
result = {k: sum(d[k] for d in dlist)
          for k in set.intersection(*[set(d) for d in dlist])}
print result

# Same as above, but as for loops
result = {}
repeated_keys = set(d1)
for d in dlist:
    repeated_keys &= set(d)
for k in repeated_keys:
    result[k] = 0
    for d in dlist:
        result[k] += d[k]
print result
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 1
    Since this is Python 3, you can use the keys directly as sets. {}.keys() is a set. – dawg Oct 04 '16 at 17:55