-1

I want to merge two dictionaries into a single dictionary with only common keys between the two.

Here are the two dictionaries

{"a": 5, "b": 8, "d": 9, "z": 4}
{"a": 1, "b": 1, "d": 2, "e": 1}

The result that I want is:

{"a": 6, "b": 9, "d": 11}

Do you guys know any way to do this?

DL_learner
  • 37
  • 5
  • 2
    What have you tried so far? – Mushif Ali Nawaz Feb 28 '21 at 04:41
  • 2
    *"Do you guys know any way to do this?"* - Yes. – superb rain Feb 28 '21 at 04:49
  • Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. "Show me how to solve this coding problem?" is off-topic for Stack Overflow. You have to make an honest attempt at the solution, and then ask a *specific* question about your implementation. Stack Overflow is not intended to replace existing tutorials and documentation. – Prune Feb 28 '21 at 04:52
  • HINT: Find the intersection of both the dictionaries(`d1.keys()&d2.keys()`), then a dictionary comprehension with required logic should do. – Ch3steR Feb 28 '21 at 04:53
  • For everyone being harsh on this question, see [here](https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) for a similar one with identical format (not duplicate), asked by a reputable user, and helpful to many people. – DV82XL Feb 28 '21 at 05:00
  • I've been trying to knacker this question for at least 2 hours off and on now. I initially tried to use the collections module and the counter to try and merge both dictionaries together before my brain just failed. I thank Prune for their suggestions along with others. I'll try to do better in the future and I know just because there are a dozen other questions like my own doesn't mean I get a free pass but I am tired. I'm sorry if I'm trying to take an easy way out and compromising my own journey towards learning programming. – Aaron Khong Feb 28 '21 at 05:25

2 Answers2

0

You can try this -

Idea is to find intersections of common keys within both of the dictionaries and sum them up from both

d1.keys() & d2.keys()


d1 = {"a": 5, "b": 8, "d": 9, "z": 4}
d2 = {"a": 1, "b": 1, "d": 2, "e": 1}

result = {key: d1[key] + d2[key] for key in d1.keys() & d2.keys()}

result
{'a': 6, 'd': 11, 'b': 9}
Vaebhav
  • 4,672
  • 1
  • 13
  • 33
0

First you need to get common keys between two dicts: Lets say you have two dicts d1 and d2

common_keys = list(set(d1.keys()).intersection(set(d2.keys())))
new_dict = {}
for key in common_keys:
    new_dict[key] = d1[key] + d2[key]
CyberPunk
  • 1,297
  • 5
  • 18
  • 35