Quantcast
Channel: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? - Stack Overflow
Browsing latest articles
Browse All 23 View Live

Answer by Prince for Is there any pythonic way to combine two dicts (adding...

dict1 = {'a':1, 'b':2, 'c':3}dict2 = {'a':3, 'g':1, 'c':4}dict3 = {} # will store new valuesfor x in dict1: if x in dict2: #sum values with same key dict3[x] = dict1[x] +dict2[x] else: #add the values...

View Article



Answer by erik258 for Is there any pythonic way to combine two dicts (adding...

Here's yet another option using dictionary comprehensions combined with the behavior of dict():dict3 = dict(dict1, **{ k: v + dict1.get(k, 0) for k, v in dict2.items() })# {'a': 4, 'b': 2, 'c': 7, 'g':...

View Article

Answer by Yann Dubois for Is there any pythonic way to combine two dicts...

Here's a very general solution. You can deal with any number of dict + keys that are only in some dict + easily use any aggregation function you want:def aggregate_dicts(dicts,...

View Article

Answer by Buoy Rina for Is there any pythonic way to combine two dicts...

One line solution is to use dictionary comprehension.C = { k: A.get(k,0) + B.get(k,0) for k in list(B.keys()) + list(A.keys()) }

View Article

Answer by A.Ranjan for Is there any pythonic way to combine two dicts (adding...

More conventional way to combine two dict. Using modules and tools are good but understanding the logic behind it will help in case you don't remember the tools.Program to combine two dictionary adding...

View Article


Answer by Lacobus for Is there any pythonic way to combine two dicts (adding...

What about:def dict_merge_and_sum( d1, d2 ): ret = d1 ret.update({ k:v + d2[k] for k,v in d1.items() if k in d2 }) ret.update({ k:v for k,v in d2.items() if k not in d1 }) return retA = {'a': 1, 'b':...

View Article

Answer by user6830669 for Is there any pythonic way to combine two dicts...

Merging three dicts a,b,c in a single line without any other modules or libsIf we have the three dictsa = {"a":9}b = {"b":7}c = {'b': 2, 'd': 90}Merge all with a single line and return a dict object...

View Article

Answer by shouldsee for Is there any pythonic way to combine two dicts...

Additionally, please note a.update( b ) is 2x faster than a + bfrom collections import Countera = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})b = Counter({'menu': 1, 'good': 1, 'bar':...

View Article


Answer by Michael Hall for Is there any pythonic way to combine two dicts...

The above solutions are great for the scenario where you have a small number of Counters. If you have a big list of them though, something like this is much nicer:from collections import CounterA =...

View Article


Answer by ragardner for Is there any pythonic way to combine two dicts...

This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only oncea = {'a':1, 'b':2, 'c':3}dicts = [{'b':3, 'c':4, 'd':5},...

View Article

Answer by Mazdak for Is there any pythonic way to combine two dicts (adding...

Definitely summing the Counter()s is the most pythonic way to go in such cases but only if it results in a positive value. Here is an example and as you can see there is no c in result after negating...

View Article

Answer by Ignacio Villela for Is there any pythonic way to combine two dicts...

This solution is easy to use, it is used as a normal dictionary, but you can use the sum function.class SumDict(dict): def __add__(self, y): return {x: self.get(x, 0) + y.get(x, 0) for x in...

View Article

Answer by PythonProgrammi for Is there any pythonic way to combine two dicts...

From python 3.5: merging and summingThanks to @tokeinizer_fsj that told me in a comment that I didn't get completely the meaning of the question (I thought that add meant just adding keys that...

View Article


Answer by Jonas Kölker for Is there any pythonic way to combine two dicts...

def merge_with(f, xs, ys): xs = a_copy_of(xs) # dict(xs), maybe generalizable? for (y, v) in ys.iteritems(): xs[y] = v if y not in xs else f(xs[x], v)merge_with((lambda x, y: x + y), A, B)You could...

View Article

Answer by schettino72 for Is there any pythonic way to combine two dicts...

For a more generic and extensible way check mergedict. It uses singledispatch and can merge values based on its types.Example:from mergedict import MergeDictclass SumDict(MergeDict):...

View Article


Answer by Adeel for Is there any pythonic way to combine two dicts (adding...

import itertoolsimport collectionsdictA = {'a':1, 'b':2, 'c':3}dictB = {'b':3, 'c':4, 'd':5}new_dict = collections.defaultdict(int)# use dict.items() instead of dict.iteritems() for Python3for k, v in...

View Article

Answer by user3804919 for Is there any pythonic way to combine two dicts...

myDict = {}for k in itertools.chain(A.keys(), B.keys()): myDict[k] = A.get(k, 0)+B.get(k, 0)

View Article


Answer by Devesh Saini for Is there any pythonic way to combine two dicts...

The one with no extra imports!Their is a pythonic standard called EAFP(Easier to Ask for Forgiveness than Permission). Below code is based on that python standard.# The A and B dictionariesA = {'a': 1,...

View Article

Answer by jeromej for Is there any pythonic way to combine two dicts (adding...

Intro:There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.Then there...

View Article

Answer by georg for Is there any pythonic way to combine two dicts (adding...

A more generic solution, which works for non-numeric values as well:a = {'a': 'foo', 'b':'bar', 'c': 'baz'}b = {'a': 'spam', 'c':'ham', 'x': 'blah'}r = dict(a.items() + b.items() + [(k, a[k] + b[k])...

View Article

Answer by Ashwini Chaudhary for Is there any pythonic way to combine two...

>>> A = {'a':1, 'b':2, 'c':3}>>> B = {'b':3, 'c':4, 'd':5}>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}>>> print(c){'a': 1, 'c': 7, 'b': 5, 'd': 5}

View Article


Answer by Martijn Pieters for Is there any pythonic way to combine two dicts...

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

View Article


Is there any pythonic way to combine two dicts (adding values for keys that...

For example I have two dicts:Dict A: {'a': 1, 'b': 2, 'c': 3}Dict B: {'b': 3, 'c': 4, 'd': 5}I need a pythonic way of 'combining' two dicts such that the result is:{'a': 1, 'b': 5, 'c': 7, 'd': 5}That...

View Article
Browsing latest articles
Browse All 23 View Live




Latest Images