B
B
blizzard2018-02-19 12:06:16
Python
blizzard, 2018-02-19 12:06:16

How to merge dictionaries by combining values ​​by key into a list?

There are many dictionaries:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
}
There is a function
z = x.update(y)
but it overwrites the value by key, and I need a list of values ​​by key in the combined dictionary, i.e.:
z = {'a': 1, 'b': [2.3] , 'c': 4]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-19
@s41blizzard

You can do this if you do not need to take into account the fact that the value of the source dictionaries may contain lists that cannot be combined into one:

def merge_dicts(*dicts):
    result = {}
    for d in dicts:
        for k,v in d.items():
            if k in result:
                if not isinstance(result[k], list):
                    result[k], t = list(), result[k]
                    result[k].append(t)
                result[k].append(v)
            else:
                result[k] = v
    return result


z = merge_dicts(x, y)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question