2017-10-16 99 views
-1

我想做一個名爲remove_short_synonyms()的函數,它傳遞了一個字典 作爲參數。參數字典的鍵是單詞,對應的值是同義詞列表。該功能可刪除同義詞的每個對應列表 以下的所有同義詞,其中的同義詞少於7個字符。python - 從字典中刪除值

如果是這樣的字典:

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']} 

如何我得到這個作爲輸出?

{beautiful : ['dazzling', 'handsome', 'magnificent', 'splendid']} 
+6

你到目前爲止試過了什麼? –

回答

2

利用詞典理解和列表理解。

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']} 
synonyms_dict = {k:[v1 for v1 in v if len(v1) >= 7] for k, v in synonyms_dict.items()} 
print(synonyms_dict) 

# {'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']} 

​ 
0

假設你有python>=3.x,對於初學者更可讀的解決辦法是:

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']} 

new_list = [] 
for key,value in synonyms_dict.items(): 
    for i in range(len(value)): 
     if len(value[i]) >= 7: 
     new_list.append(value[i]) 

synonyms_dict['beautiful'] = new_list 
print(synonyms_dict) 
2

我覺得你的問題是更適當的被評爲從列表刪除值,而不是字典

你可以使用remove,del或pop來刪除python列表中的元素。 Difference between del, remove and pop on lists

或者更Python的方式,我認爲,是

dict['beautiful'] = [item for item in dict['beautiful'] if len(item)>=7] 
+0

user1190882的答案是dict對象的更一般的解決方案,而不僅僅是一個列表對象 – Sean

0

下面是修改現有的字典,而不是取代它的功能。如果您有多個對同一字典的引用,這會很有用。

synonyms_dict = { 
    'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent'] 
} 

def remove_short_synonyms(d, minlen=7): 
    for k, v in d.items(): 
     d[k] = [word for word in v if len(word) >= minlen] 

remove_short_synonyms(synonyms_dict) 
print(synonyms_dict) 

輸出

{'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']} 

注意,此代碼替換現有列表與新的列表的字典。您可以保留舊列表對象,如果你真的需要做的是,通過改變分配線

d[k][:] = [word for word in v if len(word) >= minlen] 

儘管這將是稍微慢,而且很可能沒有理由這樣做。

0
def remove_short_synonyms(self, **kwargs): 

dict = {} 
    word_list = [] 

    for key, value in synonyms_dict.items(): 
    for v in value: 
     if len(v) > 7: 
     word_list.append(v) 
    dict[key] = word_list 

    print dict 


remove_short_synonyms(synonyms_dict)