I have a question about the dictionary in python, in the reference page: http://docs.python.org/tutorial/datastructures.html#dictionaries .
“You can’t use lists as keys, since lists can be modified in
place using index assignments, slice assignments, or methods like
append() and extend().”
But what does it mean to append the value of a python dictionary?
# 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
What exactly is going on when myDictionary[word].append(lineNumber) ? It seems to me a list, I want to be sure, the value of a key can be list (or in this case it is an Tuples)? What kind of data type exactly can be used as a value? When I want the key to store multiple values.
myDictionary[word].append(lineNumber)will call theappend()method of whatever value is stored inmyDIctionary[word]. If that value happens to be of typelist, then it will append a value to thatlist.If the value stored in
myDictionary[word]is not a list, or another sequence type implementingappend(), then callingappend()on it will be anAttributeException.