Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update python dictionary (add another value to existing key)

Tags:

python

I have simple dictionary with key, value:

d = {'word': 1, 'word1': 2}

I need to add another value (to make a list from values):

d = {'word': [1, 'something'], 'word1': [2, 'something1']}

I can't deal with it. Any clues?

like image 210
jundymek Avatar asked Jan 24 '17 10:01

jundymek


Video Answer


2 Answers

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]})
like image 36
Anshul Goyal Avatar answered Sep 19 '22 19:09

Anshul Goyal


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]
like image 76
Willem Van Onsem Avatar answered Sep 18 '22 19:09

Willem Van Onsem