I have two python dictionaries, say,
d1 = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
d2 = {'v1':'w1','v2':'w2','v5':'w5'}
what I need is a merged dict like this -
mergeDict= {k1:(v1,w1), k2:(v2,w2), k3:(v3)}
Whatever I have been able to look up or read has dealt with appending dictionaries, nothing like this. I called this chaining since value of first dict is potentially the key in second dict.
So far i have done this through typical loop and lookup on keys(). Wondering if there is a more pythonic way to achieve this that i might be missing here ?
CodePudding user response:
A dict comprehension seems to work:
out = {k: (v, d2[v]) if v in d2 else (v,) for k,v in d1.items()}
Output:
{'k1': ('v1', 'w1'), 'k2': ('v2', 'w2'), 'k3': ('v3',)}
CodePudding user response:
If you meant to merge values with the same key into a collection, you could
- create a new dict
- use
itertoolsto iterate over any number of dicts - some default value you can pack into (such as a list or set)
import itertools
d3 = {}
for key, value in itertools.chain(d1.items(), d2.items()):
d3.get(key)
try:
d3[key].append(value) # add value to list
except KeyError: # first instance of key
d3[key] = [value] # start a fresh list
Note, this doesn't meet the question as-written, which is trying to pack keys matching the same value in another dict, but share the keys between 'em
>>> d1 = {"k1":"v1","k2":"v2","k3":"v3"}
>>> d2 = {"v1":"w1","v2":"w2","v5":"w5"}
[..]
>>> d3
{'k1': ['v1'], 'k2': ['v2'], 'k3': ['v3'], 'v1': ['w1'], 'v2': ['w2'], 'v5': ['w5']}
CodePudding user response:
You can use sets and dict update with Python 3.9
>>> {k:(d1[k],) for k in d1} | {k:(d1[k],d2[k]) for k in set(d1) & set(d2)}
{'k1': ('v1', 'w1'), 'k2': ('v2', 'w2'), 'k3': ('v3',)}
