1

I also want print 10:20 in dict3. How to do this this code only print same key form dict1 and dict2. I tried this:

def mergeDicts(dict1, dict2):
    dict3 = {}
    for key, value in dict1.items():
        dict3[key] = (value, dict2[key])
    return dict3
print(mergeDicts({1:3, 2:4},{1:5, 2:6, 10:20})) 
out: {1: (3, 5), 2: (4, 6)}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
Herpes Qwe
  • 33
  • 4

1 Answers1

0

Your currently iterating just the keys/values from dict1, so the missing 10 key from dict2 will not be added.

Instead, you could merge both dictionaries with a collections.defaultdict of lists, and add the items from both dictionaries as you iterate each one. To make this flexible for any number of dictionaries, we can use *args to pass in variable length arguments.

We can also use a dictionary comprehension to convert the values to tuples at the end.

from collections import defaultdict

def mergeDicts(*dicts):
    result = defaultdict(list)

    for d in dicts:
        for k, v in d.items():
            result[k].append(v)

    return result

merged = mergeDicts({1:3, 2:4}, {1:5, 2:6, 10:20})

print({k: tuple(v) for k, v in merged.items()})

Output:

{1: (3, 5), 2: (4, 6), 10: (20,)}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75