我有一个数据字典:
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'}
我使用了 lambda
和 intersection
函数来完成此任务,但失败了
最佳答案
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/