2012-05-14 40 views
0

我可以追加到字典中的列表嗎?如何附加到字典中的列表?

test = {'food' : 'apple'} 

是否有一個命令來添加'banana'並把它變成

test = { 'food': ['apple','banana'] } 

謝謝

+2

'test ['food']。append('banana')'。 –

+1

這不是'list',它是python中的一個字符串或'str'。它在你的第二個例子中變成了一個'list'。 – jamylak

回答

4

你需要創建一個dict其中values是列表:

test = {'food' : ['apple']} 
test['food'].append('banana') 
3

最簡單的解決僅僅是隻讓你的散列表的價值,這可能只包含一個元素。再比如說,你可能有這樣的事情:

test = {'food' : ['apple']} 
test['food'].append('banana') 
+2

+1我認爲這可能是OP試圖追加,但忽略了缺失'[]' –

5

沒有,因爲它不是擺在首位的列表。

test['food'] = [test['food'], 'banana'] 
1

我建議在這種情況下使用defaultdict,這是非常簡單的對付列表的字典,從此你每次修改條目時不需要兩個單獨的案例:

import collections 

test = collections.defaultdict(list) 

test['food'].append('apple') 
test['food'].append('banana') 

print test 
# defaultdict(<type 'list'>, {'food': ['apple', 'banana']}) 
+0

沒有'defaultdict'也可以直接執行此操作:'test.setdefault(「food」,[])。append( 「蘋果」)' – kindall