0

I am trying to add new values into a key in a dictionary.

d = {'key': 'value1'}
New_values = ['value2','value3'] 

I am trying to make it look like this

d = {'key': 'value1','value2','value3'}
J.p
  • 43
  • 6

2 Answers2

3

A key in dictionary can hold only single value. The value however, can contain other values. The value can be a list, a tuple, or another dict, as well as a number or a string.

For lists:

>>> d = {'key': ['value1']}
>>> d['key'].extend(['value2', 'value3'])
>>> d
{'key': ['value1', 'value2', 'value3']}

For dicts:

>>> d = {'key': {'key1': 'value1'}}
>>> d['key']['key2'] = 'value2'
>>> d['key']['key3'] = 'value3'
>>> d
{'key': { 'key1': 'value1', 'key2: 'value2', 'key3': 'value3' }}

For strings:

>>> d = {'key': 'value1'}
>>> new_values = ['value2', 'value3']
>>> d['key'] + ',' + ','.join(new_values)
>>> d
{'key': 'value1,value2,value3' }

For tuples:

>>> d = {'key': ('value1',)}
>>> d['key'] += ('value2', 'value3')
>>> d
{'key': ('value1', 'value2', 'value3')}
Akseli Palén
  • 27,244
  • 10
  • 65
  • 75
2

You can't .append() or .extend() to a string because a string is not mutable.

If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list.

The easiest way to do this is just to add the single item as a list in the first place.

d = {'key': ['value1']}
New_values = ['value2','value3']

d['key'].extend(New_values)
d

Output:

{'key': ['value1', 'value2', 'value3']}
Drakax
  • 1,305
  • 3
  • 9