2013-11-10 96 views
0

給定一個字典,如:鑑於字典,如何替換列表中的項目?

sample_dict = {'test':['a', 'b', 'c', 'd', 'e']} 

我怎麼在列表中與別的更改的項。

例如:

def replace_item(sample_dict, item, new_item): 
     pass 

>>> replace_item({'test':['a', 'b', 'c', 'd', 'e']}, 'd', 'f') 
>>> {'test':['a', 'b', 'c', 'f', 'e']} 
+0

如果字典有多個鍵/值對,替換值是否應用於每個值或只是某個值? – jwodder

+0

假設它只有一個鍵/值。 – Sc4r

回答

0
sample_dict = {'test': ['a', 'b', 'c', 'd', 'e']} 

def replace_item(sample_dict, item, new_item): 
    list = sample_dict['test'] 
    list[list.index(item)] = new_item 

replace_item(sample_dict, 'd', 'f') 
# {'test': ['a', 'b', 'c', 'f', 'e']} 
1

你可以簡單地檢索並進行修改它,因爲字典只保存到列表中,而不是列表本身的參考。