【发布时间】:2019-06-19 19:35:55
【问题描述】:
我有两个具有匹配键和不同值的字典。我想将 a 的值添加到 b。
有些键在字典 a 但不在 b 中。我想跳过这些。
a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}
for k, v in a.items():
if k in b.keys():
list(b).append(v)
else: print 'Could not locate key', k
我希望输出是 b = {1: ["e", "a"], 2: ["b", "f"], 3: ["g","c"]}
相反,这些值没有附加。我还尝试在 v 周围使用括号,它返回
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
【问题讨论】:
-
那些在
b中但不在a中的键呢?是否要将这些键的值转换为列表?
标签: python dictionary append