MHS
MHS

Reputation: 2350

Comparing the keys and values of multiple dictionaries using python

I have a dict of my data:

data = {'Games' : ['Computer Games', 'Physical Games', 'Indoor Games', 'Outdoor Games'],
        'Mobiles' : ['Apple', 'Samsung', 'Nokia', 'Motrolla', 'HTC'],
        'Laptops' : ['Apple', 'Hp', 'Dell', 'Sony', 'Acer']}

I want to compare it with:

client_order = {'Games' : 'Indoor Games', 'Laptops' : 'Sony', 'Wallet' : 'CK', 'Mobiles' : 'HTC'}

I want to compare the keys exactly as what they are, and to iterate into the data dict's values against every matched key and may result like this:

success = {'Games' : 'Indoor Games', 'Laptops' : 'Sony', 'Wallet' : '', 'Mobiles' : 'HTC'}

I have used lambda and intersection functions to achieve this task but failed

Upvotes: 1

Views: 1180

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

What if:

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

Upvotes: 1

NPE
NPE

Reputation: 500357

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

The above only checks the key. If you also need to check whether the value is in data, you could use:

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

Upvotes: 1

Related Questions