23

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?

2
  • 4
    You can't deal with it how? Please show what you did try. You need to replace the current value with a list object. Commented Jan 24, 2017 at 10:34
  • 1
    d['word']=[d['word'],'something'] Commented Jan 24, 2017 at 10:34

8 Answers 8

31

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]
Sign up to request clarification or add additional context in comments.

Comments

22

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]})

1 Comment

defaultdict FTW
14

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]}

1 Comment

Mind that the original dictionary uses scalars, not lists.
3

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']}

Comments

2

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)

output:

Comments

1

Thanks for help. I did it that way (thanks to Willem Van Onsem advice):

x = (dict(Counter(tags))) #my dictionary
for i in x:
    color = "#%06x" % random.randint(0, 0xFFFFFF)
    x[i] = [x[i], color]

Comments

1

This is what I would do. I hope it helps. If you have a lot of items to add to your dictionary this may not be the fastest route.

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

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

d['word1']=[2, 'something1']

print(d)

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

Comments

0

you could try the below:

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

d['word1'] = [2, 'something']

call d now

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.