2017-08-07 65 views
0

有沒有更乾淨的方法來做到這一點?我可以通過列表理解來實現嗎?如果在列表中找到鍵,編輯字典值

data = {'foo': 'bar', 'twofoo': 'twobar', 'threefoo': 'threebar'} 
some_list = ['foo', 'threefoo'] 

for key in data: 
    for item in some_list: 
     if key==item: 
      data[key] = 'randomfoo' 

我想從字典 清潔值,以便「隨機富」將永遠是相同的

護理對downvotes解釋一下?

+1

如果你想檢查的關鍵是在字典中,你可以做'鍵入數據「。並且'data [key]'獲得值 –

+0

''randomfoo''會不變? – vaultah

+0

顯示所需的輸出。我相信數據缺少一個':' –

回答

3

可以拍攝列表中的字典鍵的交集,並更新值在這些按鍵:

for key in set(data).intersection(some_list): 
    data[key] = 'foobar' 

print(data) 
# {'twofoo': 'twobar', 'threefoo': 'foobar', 'foo': 'foobar'} 

你也可以定義名單爲一組,做一個快速的成員資格檢查(帶Ø(1)複雜性)對於每個鍵:

some_set = {'foo', 'threefoo'} 

for key in data: 
    if key in some_set: 
     data[key] = 'randomfoo' 
1

使用dict comprehension

res = {key: 'randomfoo' if key in some_list else value for key, value in data.items()} 

輸出:

>>> res 
{'twofoo': 'twobar', 'threefoo': 'randomfoo', 'foo': 'randomfoo'} 
0

你可以試試這個方法:

data = {'foo': 'bar', 'twofoo': 'twobar', 'threefoo': 'threebar'} 
some_list = ['foo', 'threefoo'] 

for key in data: 
    if key in some_list: 
     data[key] = "randomfoo" 

print(data) 

輸出:

{'foo': 'randomfoo', 'twofoo': 'twobar', 'threefoo': 'randomfoo'} 
相關問題