如果我想用常用值做某事而不是仅仅更新它们,那该怎么办?例如,让我们说值是一个字符串,我想在它们之间放一个简单的标签
a={'car':'ferrari','color':'red','driver':'M'}
b={'car':'lamborghini','color':'yellow','transmission':'manual'}
结果是,
merge_ab={'car':'ferrari\tlamborghini','color':'red\tyellow','driver':'M\t','transmission':'\tmanual'}
答案 0 :(得分:3)
这是一个很好的Pythonic方法:
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)
答案 1 :(得分:2)
您可以先合并dicts,然后分别处理公共密钥:
merge_ab = dict(a, **b)
for key in set(a) & set(b):
merge_ab[key] = '{0}\t{1}'.format(a[key], b[key])
如果您使用的是Python 2.7,则可以使用效率更高的a.viewkeys() & b.viewkeys()
代替set(a) & set(b)
。
答案 2 :(得分:1)
试试这个,它将在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'}
如果要使用迭代器,请在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()))}
等效地,在Python 3.x中执行此操作:
{ k:a.get(k,'') + '\t' + b.get(k,'') for k in set(it.chain(a.keys(), b.keys())) }
答案 3 :(得分:0)
这样的东西?请注意,这会修改字典b
,这可能不是您想要的;如果您想创建一个新词典,那么只需分配一个:c={ }
并将项目排序。
>>> 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'}