Reputation: 197
Hi what if i wanted to do something with the common values instead of just updating them. For instance lets the say the value is a string and i wanted to put a simple tab between them
a={'car':'ferrari','color':'red','driver':'M'}
b={'car':'lamborghini','color':'yellow','transmission':'manual'}
such that the result is,
merge_ab={'car':'ferrari\tlamborghini','color':'red\tyellow','driver':'M\t','transmission':'\tmanual'}
Upvotes: 1
Views: 113
Reputation: 1171
Here's a nice Pythonic way to do it:
dicts = [a, b]
allKeys = set(k for d in dicts for k in d.iterkeys())
makeValue = lambda k: '\t'.join(d.get(k, '') for d in dicts) # Make merged value for a given key
merged = dict((k,makeValue(k)) for k in allKeys)
Upvotes: 3
Reputation: 236114
Try this, it will work in Python 2.x:
{ k:a.get(k, '') + '\t' + b.get(k, '') for k in set(a.keys() + b.keys()) }
=> {'color': 'red\tyellow', 'car': 'ferrari\tlamborghini',
'driver': 'M\t', 'transmission': '\tmanual'}
If you want to use iterators, do this in Python 2.x:
import itertools as it
{k:a.get(k,'')+'\t'+b.get(k,'') for k in set(it.chain(a.iterkeys(),b.iterkeys()))}
Equivalently, do this in Python 3.x:
{ k:a.get(k,'') + '\t' + b.get(k,'') for k in set(it.chain(a.keys(), b.keys())) }
Upvotes: 1
Reputation: 9130
Something like this? Note that this modifies the dictionary b
which might not be what you want; if you'd like to create a new dictionary, then just allocate one: c={ }
and sort the items into it.
>>> a={'car':'ferrari','color':'red','driver':'M'}
>>> b={'car':'lamborghini','color':'yellow','transmission':'manual'}
>>> for k, v in a.items() : # Iterate over all key, item pairs of the a dictionary.
... if k in b : # If a given key exists in the b dictionary as well, then...
... b[k] += "\\" + v # ...merge the two items.
... else : # Else, if the given key does not exist in the b dictionary, then...
... b[k] = v # ...add it.
...
>>> b
{'color': 'yellow\\red', 'car': 'lamborghini\\ferrari', 'transmission': 'manual', 'driver': 'M'}
Upvotes: 0
Reputation: 318578
You could merge the dicts first and then handle common keys separately:
merge_ab = dict(a, **b)
for key in set(a) & set(b):
merge_ab[key] = '{0}\t{1}'.format(a[key], b[key])
If you are using Python 2.7 you can use the more efficient a.viewkeys() & b.viewkeys()
instead of set(a) & set(b)
.
Upvotes: 2