Steve Grafton
Steve Grafton

Reputation: 1961

python dictionary adding to an existing key

I am trying to add items to a dictionary. I have already tried many of the things that have been suggested but nothing seems to be working. This is my current version of the code.

For key "1", there will be three entries. But as I go through a list and try adding items to key '1", it simply replaces the value not append.

Upvotes: 0

Views: 260

Answers (1)

falsetru
falsetru

Reputation: 369444

Try following:

>>> d = {}
>>> d.setdefault('1', []).append('x')
>>> d.setdefault('1', []).append('y')
>>> d.setdefault('1', []).append('z')
>>> d
{'1': ['x', 'y', 'z']}

or using collections.defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['1'].append('x')
>>> d['1'].append('y')
>>> d['1'].append('z')
>>> d
defaultdict(<type 'list'>, {'1': ['x', 'y', 'z']})

Upvotes: 1

Related Questions