gpt4 book ai didi

如果存在匹配,Python 将 dict 中的值附加到具有两个值的现有 dict 中

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:39 24 4
gpt4 key购买 nike

a = {('a', 'b', 'c'): [4, 5], ('d', 'e', 'f'): [0, 1]}
b = {('a', 'b', 'c'): 4, ('z', 'z', 'z'): 1, ('d', 'e', 'f'): 1}
c = {key:[val,b.get(key,0)] for key,val in a.items()}
print(c)

输出:

{('a', 'b', 'c'): [[4, 5], 4], ('d', 'e', 'f'): [[0, 1], 1]}

如何附加值而不创建看起来像这样的新值数组 - [[0, 1], 1]

我想要得到的是:

{('a', 'b', 'c'): [4, 5, 4], ('d', 'e', 'f'): [0, 1, 1]}

最佳答案

append value from dict to existing dict with two value if there is a match

在你的例子中,a是一个“源”字典,b是一个“接收者”字典.
使用列表连接的简单解决方案:

a = {('a', 'b', 'c'): [4, 5], ('d', 'e', 'f'): [0, 1]}
b = {('a', 'b', 'c'): 4, ('z', 'z', 'z'): 1, ('d', 'e', 'f'): 1}
c = {k:v + [b[k]] for k,v in a.items() if k in b}

print(c)

输出:

{('d', 'e', 'f'): [0, 1, 1], ('a', 'b', 'c'): [4, 5, 4]}

关于如果存在匹配,Python 将 dict 中的值附加到具有两个值的现有 dict 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42329407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com