Python's append() only allows unique items in a list?
append, data-structures, python
Solution
There is no second word2.
>>> d = {}
>>> d["word1"] = 1
>>> d["word2"] = 2
>>> d
{'word1': 1, 'word2': 2}
>>> d["word2"] = 3
>>> d
{'word1': 1, 'word2': 3}
Dictionaries map a specific key to a specific value. If you want a single key to correspond to multiple values, typically a list is used, and a defaultdict comes in very handy:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["word1"].append(1)
>>> d["word2"].append(2)
>>> d["word2"].append(3)
>>> d
defaultdict(<type 'list'>, {'word1': [1], 'word2': [2, 3]})
Problem
The python documentation implies that duplicate items can exist within a list, and this is supported by the assignmnet: list = ["word1", "word1"]. However, Python's append() doesn't seem to add an item if it's already in the list. Am I missing something here or is this a deliberate attempt at a set() like behaviour? ``` >> d = {} >> d["word1"] = 1 >> d["word2"] = 2 >> d["word2"] = 3 >> vocab = [] >> for word,freq in d.iteritems(): >> ... vocab.append(word) >> for item in vocab: >> ... print item ``` returns: ``` word1 word2 ``` Where's the second word2?