Is There Any Pythonic Way to Combine Two Dicts (Adding Values For Keys That Appear in Both)

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Use collections.Counter:

>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})

Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.

How to merge multiple dicts with same key or different key?

assuming all keys are always present in all dicts:

ds = [d1, d2]
d = {}
for k in d1.iterkeys():
d[k] = tuple(d[k] for d in ds)

Note: In Python 3.x use below code:

ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)

and if the dic contain numpy arrays:

ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = np.concatenate(list(d[k] for d in ds))

Python program to combine two dictionary adding values for common keys

I like Andrej's answer (I LOVE list/dict comprehensions), but here's yet another thing:

d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}

d3 = dict(d1) # don't do `d3=d1`, you need to make a copy
d3.update(d2)

for i, j in d1.items():
for x, y in d2.items():
if i == x:
d3[i]=(j+y)


print(d3)

I realised your own code can be "fixed" by first copying values from d1 and d2.

d3.update(d2) adds d2's contents to d3, but it overwrites values for common keys. (Making d3's contents {'a':300, 'b':200, 'c':300, 'd':400})

However, by using your loop after that, we correct those common values by assigning them the sum. :)

How to merge two dicts and combine common keys?

A solution, without importing anything:

# First initialize data, done correctly here.
D1 = [{'k1': 'v01'}, {'k3': 'v03'}, {'k4': 'v04'}]
D2 = [{'k1': 'v11'}, {'k2': 'v12'}, {'k4': 'v14'}]

# Get all unique keys
keys = {k for d in [*D1, *D2] for k in d}

# Initialize an empty dict
D3 = {x:[] for x in keys}

# sort to maintain order
D3 = dict(sorted(D3.items()))

#Iterate and extend
for x in [*D1, *D2]:
for k,v in x.items():
D3[k].append(v)

# NOTE: I do not recommend you convert a dictionary into a list of records.
# Nonetheless, here is how it would be done.
# To convert to a list
D3_list = [{k:v} for k,v in D3.items()]

print(D3_list)

# [{'k1': ['v01', 'v11']},
# {'k2': ['v12']},
# {'k3': ['v03']},
# {'k4': ['v04', 'v14']}]

Add values from two dictionaries

this is a one-liner that would do just that:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}

note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise.


this works on a more recent python version:

{k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}

Merge two dicts with the same keys but add as another value (not replace)

A dictionary comprehension will solve this (I correctly formatted your dictionary definitions from the question, tested with Python 3.8.0):

>>> dict_1 = {'a': {'price': 4000}, 'b': {'price': 14000} }
>>> dict_2 = {'a': {'discount': 100}, 'b': {'discount': 400} }
>>> merged_dict = {k: { **dict_1[k], **dict_2[k] } for k in dict_2.keys()}
>>> merged_dict
{'a': {'price': 4000, 'discount': 100}, 'b': {'price': 14000, 'discount': 400}}

Is there a better way to merge two dicts of sets?

You are using defaultdicts. So you don't need the if/else... Just do:

def merge_dict(source_dict, target_dict):
for source_key, source_value in source_dict.items():
target_dict[source_key].update(source_value)

If the source_key is not in target_dict, an empty set will be created and immediately updated. That's exactly the use-case for defaultdicts...

Python: Merge 2 dictionaries and add 0 if key is empty

You can get the list of keys then generate the required dictionary by using dict.get and default value as 0

d1 = {'a':2, 'b':4}
d2 = {'a':13, 'b':3, 'c':5}

keys = set((*d1.keys(), *d2.keys()))

new_dict = {k: [d.get(k, 0) for d in [d1, d2]] for k in keys}

print(new_dict) #{'a': [2, 13], 'b': [4, 3], 'c': [0, 5]}


Related Topics



Leave a reply



Submit