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

1 投票
2 回答
1176 浏览
提问于 2025-04-17 18:54

我有一个包含我数据的字典:

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 个回答

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

撰写回答