Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's append() only allows unique items in a list?

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?

like image 692
Zach Avatar asked Mar 28 '26 19:03

Zach


1 Answers

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]})
like image 130
DSM Avatar answered Mar 30 '26 11:03

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!