【发布时间】:2020-07-31 06:45:49
【问题描述】:
我尝试在 SO 中进行一些搜索以找到解决方案,但我仍然感到困惑。我认为我从根本上误解了循环、列表和字典。
我基本上是自学成才,绝不是专家,所以如果这是一个非常愚蠢的问题,请提前道歉。
我有各种字典列表,例如下面 sn-p 中的 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}]
这就是我所拥有的(cmets 解释我认为代码是/应该做什么)
# 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() 并最终得到一个字典元组列表,这让我觉得我要么使用不正确,要么它对于我需要的工具来说太复杂了。 根据我在做一些研究时的理解,问题是我一直在覆盖我刚刚写的值,我认为这就是为什么我总是最终只在任何地方添加最后一个值。
任何帮助表示赞赏!
【问题讨论】:
标签: python list loops dictionary