Update python dictionary (add another value to existing key)

Well you can simply use:

d['word'] = [1,'something']

Or in case the 1 needs to be fetched:

d['word'] = [d['word'],'something']

Finally say you want to update a sequence of keys with new values, like:

to_add = {'word': 'something', 'word1': 'something1'}

you could use:

for key,val in to_add.items():
    if key in d:
        d[key] = [d[key],val]

It will be easiest if you always use lists, even when you just have a single value. It will just be a list of length 1.

>>> d = {'a': [1], 'b': [2]}
>>> d
{'a': [1], 'b': [2]}
>>>
>>> d['a'].append(5)
>>> d
{'a': [1, 5], 'b': [2]}

You could write a function to do this for you:

>>> d = {'word': 1, 'word1': 2}
>>> def set_key(dictionary, key, value):
...     if key not in dictionary:
...         dictionary[key] = value
...     elif type(dictionary[key]) == list:
...         dictionary[key].append(value)
...     else:
...         dictionary[key] = [dictionary[key], value]
... 
>>> set_key(d, 'word', 2)
>>> set_key(d, 'word', 3)
>>> d
{'word1': 2, 'word': [1, 2, 3]}

Alternatively, as @Dan pointed out, you can use a list to save the data initially. A Pythonic way if doing this is you can define a custom defaultdict which would add the data to a list directly:

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

Tags:

Python