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

The python documentation assumes that duplicate elements can exist in a list, and this is supported by assignmnet: list = ["word1", "word1"]. However, Python append () does not seem to add an element if it is already in the list. Am I missing something here or is this a deliberate attempt to set () as behavior?

>> 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 is the second word2?

+3
source share
7 answers

The second word2 is missing.

>>> d = {}
>>> d["word1"] = 1
>>> d["word2"] = 2
>>> d
{'word1': 1, 'word2': 2}
>>> d["word2"] = 3
>>> d
{'word1': 1, 'word2': 3}

Dictionaries display a specific key for a specific value. If you want a single key to correspond to several values, a list is usually used, and the defaultdict parameter is very convenient:

>>> 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]})
+8
source

. , , , . , , .

>>> d = {}
>>> d['word1'] = 1
>>> d['word2'] = 2
>>> d['word2'] = 3
>>> print d
{'word1': 1, 'word2': 3}

, :

>>> words = ['word1', 'word2', 'word2']
>>> newlist = []
>>> for word in words:
...     newlist.append(word)
... 
>>> newlist
['word1', 'word2', 'word2']
+3

"word2", dict . -.

, , dict dict.keys().

+1

( ). dict :

In [5]: d
Out[5]: {'word1': 1, 'word2': 3}

word2 . dict .

0

append(), , , .

This means that the line d["word2"] = 3does not add an additional key "word2", it overwrites the current value d["word2"].

0
source

Since d is a dictionary, the key can have only one value, so when changing d["word2"] = 2and then d["word2"] = 3you rewrite the value 2 with 3.

>> d = {}
>> d["word1"] = 1
>> d["word2"] = 2
>> d["word2"] = 3

#the fourth line `d["word2"] = 3` only modifies the value of d["word2"].

>> print(d)
{'word1': 1, 'word2': 3}
0
source

The dictionary displays duplicate keys and overwrites the older record by the last entered record.

>>> d = {}
>>> d["word1"] = 1
>>> d
{'word1': 1}
>>> d["word2"] = 2
>>> d
{'word1': 1, 'word2': 2}
>>> d["word2"] = 3
>>> d
{'word1': 1, 'word2': 3}
0
source

All Articles