在python中根据键值组合字典
让我们假设,我在python中有一个键值对,如下所示在python中根据键值组合字典,python,dictionary,Python,Dictionary,让我们假设,我在python中有一个键值对,如下所示 a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]} 现在,我想将这些值与以下内容结合起来: b = {'44': ['test1'], '43': ['test2']} 如何用python实现下面的输出 c = {'44': [0, 0, 1, 0, 1, 'test1], '43': [0, 0, 1, 0, 0,'test2']} 输出: {'44': [0, 0, 1, 0, 1,
a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]}
现在,我想将这些值与以下内容结合起来:
b = {'44': ['test1'], '43': ['test2']}
如何用python实现下面的输出
c = {'44': [0, 0, 1, 0, 1, 'test1], '43': [0, 0, 1, 0, 0,'test2']}
输出:
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'test1': [0, 0, 1, 0, 1], 'test2': [0, 0, 1, 0, 0]}
您可以使用这样的字典理解(从Python 2.7+开始): 这假定
a
和b
中存在相同的键。
如果情况并非如此,则可以在必要时解决这一问题。您可以使用字典理解功能,在一行代码中实现这一点,如下所示:
c = {k: v for k, v in zip(a.keys(), (v1 + v2 for v1, v2 in zip(a.values(), b.values())))}
输出:
>>> c
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
其他答案基于这样一个假设:所有涉及的词典都有相同的键。如果您不确定情况是否如此,我建议使用:
此外,此解决方案适用于任意数量的词典。只需将所有要合并的词典添加到元组
(a,b)
我想到的第一件事是:
c = {k: a.get(k, []) + b.get(k, []) for k in {*a.keys(), *b.keys()}}
即使一个dict中缺少一些键,这也应该有效。不过我认为这只适用于较新版本的python 3。我在这里假设
a
和b
包含相同的键。然后您可以简单地使用dict comprehension():
如果您不知道b
是否具有相同的键,您也可以测试:
c = {x: a[x] + b[x] for x in a if x in b}
您可以尝试以下方法:
a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]}
b = {'44': ['test1'], '43': ['test2']}
final_data = {c:a[c]+b[c] for c, d in a.items()}
l1 = {}
for c, d in a.items():
if d not in l1.values():
l1["test{}".format(len(l1)+1)] = d
print(l1)
输出:
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'test1': [0, 0, 1, 0, 1], 'test2': [0, 0, 1, 0, 0]}
如果需要生成“test1”、“test2”值等,可以尝试以下方法:
a = {'44': [0, 0, 1, 0, 1], '43': [0, 0, 1, 0, 0]}
b = {'44': ['test1'], '43': ['test2']}
final_data = {c:a[c]+b[c] for c, d in a.items()}
l1 = {}
for c, d in a.items():
if d not in l1.values():
l1["test{}".format(len(l1)+1)] = d
print(l1)
输出:
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'44': [0, 0, 1, 0, 1, 'test1'], '43': [0, 0, 1, 0, 0, 'test2']}
{'test1': [0, 0, 1, 0, 1], 'test2': [0, 0, 1, 0, 0]}
可能重复这种情况