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

时间:2013-03-13 08:10:10

标签: 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函数来完成此任务但失败了

2 个答案:

答案 0 :(得分:1)

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': ''}

以上只检查密钥。如果您还需要检查值是否在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': ''}

答案 1 :(得分:1)

如果:

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 = {}
for k,v in client_order.items():
    if k in data and v in data[k]:
        success[k] = v
    elif k not in data:
        success[k] = ''