简体   繁体   中英

Is there any pythonic way to combine two dicts (making a list for common values)?

For example, I have two dicts.

A = {'a':1, 'b':10, 'c':2}
B = {'b':3, 'c':4, 'd':10}

I want a result like this:

{'a':1, 'b': [10, 3], 'c':[2, 4], 'd':10}

If a key appears in both the dicts, I want to list of both the values.

I'd make all values lists:

{k: filter(None, [A.get(k), B.get(k)]) for k in A.viewkeys() | B}

using dictionary view objects .

Demo:

>>> A = {'a':1, 'b':10, 'c':2}
>>> B = {'b':3, 'c':4, 'd':10}
>>> {k: filter(None, [A.get(k), B.get(k)]) for k in A.viewkeys() | B}
{'a': [1], 'c': [2, 4], 'b': [10, 3], 'd': [10]}

This at least keeps your value types consistent.

To produce your output, you need to use the set intersection and symmetric differences between the two dictionaries:

dict({k: [A[k], B[k]] for k in A.viewkeys() & B},
     **{k: A.get(k, B.get(k)) for k in A.viewkeys() ^ B})

Demo:

>>> dict({k: [A[k], B[k]] for k in A.viewkeys() & B},
...      **{k: A.get(k, B.get(k)) for k in A.viewkeys() ^ B})
{'a': 1, 'c': [2, 4], 'b': [10, 3], 'd': 10}

In Python 3, dict.keys() is a dictionary view, so you can just replace all .viewkeys() calls with .keys() to get the same functionality there.

I would second the notion of Martijn Pieters that you problably want to have the same type for all the values in your result dict.

To give a second option:

you could also use the defaultdict to achieve your result quite intuitively.

a defaultdict is like a dict, but it has a default constructor that is called if the key doesn't exist yet.

so you would go:

from collections import defaultdict

A = {'a':1, 'b':10, 'c':2}
B = {'b':3, 'c':4, 'd':10}

result = defaultdict(list)

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

then in a later stage you still easily add more values to your result.

you can also switch to

defaultdict(set)

if you don't want duplicate values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM