bou*_*sle 5 python dictionary loops list
我尝试在 SO 中进行一些搜索以找到解决方案,但我仍然感到困惑。我认为我从根本上误解了循环、列表和字典。
我主要是自学的,绝不是专家,所以如果这是一个非常愚蠢的问题,请提前道歉。
我有各种字典列表,例如下面代码段中的 l1 和 l2 示例。我想要的输出是这样的
l3 = [{'A':1, 'B':4},{'A':2,'B':5},{'A':3,'B':6}
Run Code Online (Sandbox Code Playgroud)
但是,无论我尝试什么,我似乎总是只从第二个字典中获取最后一个键值对,即
[{'A': 1, 'B': 6}, {'A': 2, 'B': 6}, {'A': 3, 'B': 6}]
Run Code Online (Sandbox Code Playgroud)
这就是我所得到的(评论来解释我认为代码是/应该做什么)
# 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)
Run Code Online (Sandbox Code Playgroud)
我也尝试使用 zip() 并最终得到一个字典元组列表,这让我觉得我要么使用不正确,要么它对于我在这里需要的工具来说太复杂了。根据我在做一些研究时所理解的,问题是我一直覆盖我刚刚编写的值,我认为这就是为什么我始终只在所有地方添加最后一个值。
任何帮助表示赞赏!
这应该可以用一行代码完成:
# 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)
# add dictionaries for dictionaries in zipped list1 and list2
l3 = [dict(d1, **d2) for d1, d2 in zip(l1, l2) ]
print(l3)
Run Code Online (Sandbox Code Playgroud)
输出:
[{'A': 1}, {'A': 2}, {'A': 3}]
[{'B': 4}, {'B': 5}, {'B': 6}]
[{'A': 1, 'B': 4}, {'A': 2, 'B': 5}, {'A': 3, 'B': 6}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |