2014-09-25 70 views
0

對不起,如果這是一個noob問題,但我是新手編程和python,這就是爲什麼我問。如何給字典Python添加值

我想將值添加到我的字典鍵。

我有詞典:

dictio = {"Object": "Computer"} 

現在關鍵「對象」內,我想補充的價值「鼠標」

所以最終的結果我期待的是:

>>> dictio 
>>> {"Object": ["Computer", "Mouse"]} 
+0

你的字典中的結果是無效的 – karthikr 2014-09-25 01:57:43

+0

@karthikr ..你是什麼意思? – Andre 2014-09-25 02:00:26

+0

您是否在嘗試[Google](http://www.google.com)之前先試過? – 2014-09-25 02:00:44

回答

1

一個可行的方法:

dictio = {"Object": ["Computer"]} 

dictio["Object"].append("mouse") 
0

不能對字符串進行列表操作:

>>> 'string'.append('addition') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'append' 

你如果支持添加,只能向數據結構添加內容:

>>> li=['string'] 
>>> li.append('addition') 
>>> li 
['string', 'addition'] 

你想利用與另一個字符串相關的字符串組成的字典:

dictio = {"Object": "Computer"} 

,並加入到它,就好像它是一個列表。與上面相同的問題:

>>> dictio["Object"].append("Mouse") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'str' object has no attribute 'append' 

怎麼辦?如果字典中的對象是一個字符串,它需要是一個附加到它的列表。

您可以先測試:

>>> if isinstance(dictio["Object"], list): 
... dictio["Object"].append('Mouse') 
... else: 
... dictio["Object"]=[dictio["Object"]] 
... dictio["Object"].append('Mouse') 
... 
>>> dictio 
{'Object': ['Computer', 'Mouse']} 

或者嘗試和應對故障:

try: 
    dictio["Object"].append("Mouse") 
except AttributeError: 
    dictio["Object"]=[dictio["Object"]] 
    dictio["Object"].append("Mouse")  
2

您的配方似乎表明你沒有掌握正確的是什麼字典的蟒蛇。這也使我們很難理解你想要什麼。

例如:

I want to add values to my dictionary keys. 

是不明確的(至少),可以在幾個方面進行解釋。我會解釋下面的答案中含糊不清的內容。

即使你原來的例子是沒有幫助的,因爲它是無效的語法:

>>> {"Object": "Computer", "Mouse"} 
SyntaxError: invalid syntax 

字典的詞彙量約關鍵

字典只有一個

因此,您需要回答以下問題:什麼是"Mouse"?一個密鑰dictio,或它們中沒有一個?

要麼你想:

>>> {"Object": "Computer", "Mouse": "A Sample Value"} 

這是一雙新關鍵/的字典。這是可以做到這樣的:

>>> dictio["Mouse"] = "A Sample Value" 

或者,也許你想另一個「添加」到已存儲在字典中的關鍵"Object"。但是,「加」 A 字典一個說話的時候是模糊的,因爲字典只保存一個一個關鍵

  • 你想當前字符串到一個新級聯?
  • 還是你想用列表以取代目前字符串? (如果是的話,你的起始應該是第一個元素的列表)。

產生的字典使用列表關鍵"Object"是:

>>> {"Object": ["My Computer", "Mouse"]} 

因此,這仍將是一個關鍵字典,與一個。這恰好是列表,這意味着它的自我,它可以在一個特定的順序容納多個內

注意,如果我想從您的原始dictio開始變得與之前的結果,我不得不更換價值"Computer"(類型)與不同類型的不同值:["My Computer", "Mouse"](它是一個列表值爲)。

所以可以這樣做是這樣的:

>>> dictio["Object"] = [dictio["Object"], "Mouse"] 

但是,這不是很自然,你可能會想開始一個dictio這樣的:

>>> dictio = {"Object": ["Mouse"]} 

那麼,「增加'列表不再含糊不清。然後它也將是更簡單的實現:

>>> dictio["Object"].append("Mouse") 

希望看完這有助於你更好地把握什麼是類型的字典的蟒蛇。您應該找到有關字典的教程或基本文檔,因爲您似乎錯過了一些基本概念。