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 = {'Games' : 'Indoor Games', 'Laptops' : 'Sony', 'Wallet' : '', 'Mobiles' : 'HTC'}

我已经使用lambdaintersection函数来完成这个任务但失败了

4

2 回答 2

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': ''}
于 2013-03-13T08:13:08.330 回答
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] = ''
于 2013-03-13T08:14:42.963 回答