我有一個關於python中的字典的問題,在參考頁面:http://docs.python.org/tutorial/datastructures.html#dictionaries。追加到Python的字典鍵值:
「你不能使用列表作爲密鑰,因爲鏈表可以 代替使用索引分配,切片分配或方法進行修飾等 追加()和extend()」。
但是,追加python字典的值是什麼意思?
# A simple program that keep track of the line number(s) a word appeared in the novel
myDictionary = {}
with open('novel.txt') as book:
lineNumber = 1
for line in book:
# cleaned is a helper function to clean up the line
for word in cleaned(line).split():
if word in myDictinoary:
myDictionary[word].append(lineNumber)
else:
myDiciontary[word]=[lineNumber]
lineNumber += 1
myDictionary[word].append(lineNumber)
究竟發生了什麼?在我看來,列表中,我想確定,一個鍵的價值可以列表(或在這種情況下,它是一個元組)? 什麼樣的數據類型可以用作值?當我想要密鑰存儲多個值時。
關於無法使用列表作爲字典*鍵*的引用與您的文章的其餘部分無關,即修改字典*值*。您不能使用可變對象(包括列表)作爲關鍵字,因爲更改關鍵字會破壞字典查找。你可以使用任何你想要的價值。 – 2012-03-18 05:20:19
是的,我問的原因是因爲我沒有看到它隱含地告訴我「任何物體都可以用作價值」。它只是說什麼不能用於鑰匙,現在我想我明白了。 – George 2012-03-18 05:27:35