我试着在SO上搜寻解决方案,但还是没能解决问题。我觉得我对于循环、列表和字典的基础理解有误。
我大多是自学的,远非专家,所以提前道歉,如果这是一个非常愚蠢的问题。
我有各种各样的字典列表,如下面代码段中的l1和l2示例。 我期望的输出结果像这样
l3 = [{'A':1, 'B':4},{'A':2,'B':5},{'A':3,'B':6}
然而,无论我尝试什么,似乎总是只从第二个字典中获取最后一个键值对,即。
[{'A': 1, 'B': 6}, {'A': 2, 'B': 6}, {'A': 3, 'B': 6}]
这是我得到的(注释说明了代码应该做什么)
# First list of dictionaries
l1 = [{'A': 1},{'A': 2},{'A': 3}]
print(l1)
# Second list of dictionaries
l2 = [{'B': 4},{'B': 5},{'B': 6}]
print(l2)
# Empty list - to receive dictionaries in l1 and l2
l3 =[]
print(l3)
# Adding dictionaries from l1 into l3
for dict1 in l1:
l3.append(dict1)
print(l3)
# Opening l3 to loop through each dictionary, using range(len()) to loop through the index positions
for i in range(len(l3)):
# Opening l2 to loop through each dictionary
for dict2 in l2:
l3[i].update(dict2)
print(l3)
# Tried inverting the lists here, looping through l2 and then looping through l3 to append all dictionaries in l2
for dict2 in l2:
for i in range(len(l3)):
l3[i].update(dict2)
print(l3)
我曾尝试使用zip(),但最终得到了一系列由字典组成的元组列表,这让我觉得我可能在错误地使用它,或者它对我在这里所需的功能来说过于复杂。 通过做一些研究,我所理解的问题是我不断地覆盖我刚刚写入的值,我认为这就是为什么每次最终只得到了添加的最后一个值的原因。
欢迎任何帮助!