2013-03-13 50 views
0

鍵和多本字典的值我有我的數據字典:比較使用python

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

我有使用d lambdaintersection函數來實現這一任務,但未能

+0

你會在乎分享您失敗的嘗試?它可能有任何問題可以指出,你可以從中學習... – 2013-03-13 08:17:18

回答

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

如果:

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