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?
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]
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]})
defaultdict FTWIt 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 can create your dictionary assigning a list to each key
d = {'word': [1], 'word1': [2]}
and then use the following synthases to add any value to an existing key or to add a new pair of key-value:
d.setdefault(@key,[]).append(@newvalue)
For your example will be something like this:
d = {'word': [1], 'word1': [2]}
d.setdefault('word',[]).append('something')
d.setdefault('word1',[]).append('something1')
d.setdefault('word2',[]).append('something2')
print(d)
{'word': [1, 'something'], 'word1': [2, 'something1'], 'word2': ['something2']}
This works for me without the need to import anything or setdefaults python3
gear = {
'Cameras': ['77D','SL2'],
'Lens': ['10mm','18-55mm', '50mm', '70-250mm'],
'Mounts': ['Monopod', 'Tripod']
}
def dump(dictionary):
print('Camera Gear: \n')
for key, value in dictionary.items():
print(key, value)
dump(gear)
gear['Mounts'].append('Gimbal')
dump(gear)
d['word']=[d['word'],'something']