gpt4 book ai didi

python - 使用python比较多个字典的键和值

转载 作者:行者123 更新时间:2023-12-01 05:48:10 24 4
gpt4 key购买 nike

我有一个数据字典:

data = {'Games' : ['Computer Games', 'Physical Games', 'Indoor Games', 'Outdoor Games'],
'Mobiles' : ['Apple', 'Samsung', 'Nokia', 'Motrolla', 'HTC'],
'Laptops' : ['Apple', 'Hp', 'Dell', 'Sony', 'Acer']}

我想将其与以下内容进行比较:

client_order = {'Games' : 'Indoor Games', 'Laptops' : 'Sony', 'Wallet' : 'CK', 'Mobiles' : 'HTC'}

我想准确地比较键,并针对每个匹配的键迭代数据字典的值,可能会产生如下结果:

success = {'Games' : 'Indoor Games', 'Laptops' : 'Sony', 'Wallet' : '', 'Mobiles' : 'HTC'}

我使用了 lambdaintersection 函数来完成此任务,但失败了

最佳答案

In [15]: success = {k:(v if k in data else '') for (k,v) in client_order.items()}

In [16]: success
Out[16]: {'Games': 'Indoor Games', 'Laptops': 'Sony', 'Mobiles': 'HTC', 'Wallet': ''}

以上仅检查 key 。如果您还需要检查该值是否在 data 中,您可以使用:

In [18]: success = {k:(v if v in data.get(k, []) else '') for (k,v) in client_order.items()}

In [19]: success
Out[19]: {'Games': 'Indoor Games', 'Laptops': 'Sony', 'Mobiles': 'HTC', 'Wallet': ''}

关于python - 使用python比较多个字典的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15379944/

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