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?
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]})
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With