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

标签 python dictionary

我有一个数据字典:

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/

相关文章:

python - 如何在 python 中将超大数与超小数相乘?

python - Pandas 在另一列中出现某个值之前选择行的子集

python - 当我为 Linux 和 Windows 开发 python 代码时,我需要考虑什么?

c++ - C++ 中的非法间接寻址

c# - 如何通过删除旧元素来清理字典

python - 如何构建十六进制命令并将其发送到电视

python - 看起来冗余的模块和类名称

python - 创建和查找每个值具有多个键的 2D 字典

arrays - 在 Swift 中创建具有自变量的 "grid"项?

dictionary - 有没有一种惯用的方法可以在 Clojure 的 map 中找到匹配的键和值?