gpt4 book ai didi

python - 如何从现有字典中有选择地创建字典?

转载 作者:行者123 更新时间:2023-12-02 18:53:43 25 4
gpt4 key购买 nike

我有两个像下面这样的字典,它们有共同的键:

dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}

仅当 dictionary2 键的对应值具有 “yes” 时,我才想使用 dictionary1 的键和值创建一个新字典>.

预期输出:

{2: 'b', 3: 'c'}

我尝试过的:

dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}
common_pairs = dict()

for key,value in dictionary2.items():
for key,v in dictionary1.items():
if(value == "yes"):
common_pairs[key] = v

最佳答案

您不需要嵌套的 for 循环。只需对 dictionary1 项进行一次迭代,并在 dictionary2 中进行相应的 O(1) 查找:

使用 dict 理解,这看起来像:

>>> dictionary1 = {1: 'a', 2: 'b' , 3: 'c'}
>>> dictionary2 = {1: 'no', 2: 'yes' ,3:'yes'}
>>> new = {k: v for k, v in dictionary1.items() if dictionary2[k] == 'yes'}
>>> new
{2: 'b', 3: 'c'}

使用传统的 for 循环:

>>> new = {}
>>> for k, v in dictionary1.items():
... if dictionary2[k] == 'yes':
... new[k] = v
...
>>> new
{2: 'b', 3: 'c'}

关于python - 如何从现有字典中有选择地创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66428328/

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