Python Forum

Full Version: dict value, how to change type from int to list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a dictionary, and one of the keys currently has 1 as value, so the value side is an int. I'm trying to make the value side a list so it can have [1, 2].

I currently have: {'key1': 1}
I'm trying to get: {'key1': [1, 2]}

test = dict()
test['key1'] = 1

# i tried without success:
# this will do an addition
test['key1'] += 2
# this will replace the current value
test.update({'key1': 2})
thank you!
If it's just this one case, just replace it.

test['key1'] = [test['key1'], 2]
The problem is if you need to do this and might want to keep extending the list. Best in that case is to never insert the int in the first place. Always have a list as the value (perhaps via defaultdict). Then you can just append whenever necessary.

import defaultdict
test = defaultdict(list)

#first element
test['key1'].append(1)
# second element
test['key1'].append(2)
test = {'key':[1] }  # Initialize with a list value
test['key'] += [2]  # Then you can add to the list like this
test['key'].append(3)  # or this
test['key'].extend((4, 5, 6))  # or this
print(test['key'])
Output:
[1, 2, 3, 4, 5, 6]
One way is to use setdefault.

>>> test = dict()
>>> test.setdefault('key1', list()).append(2)
>>> test
{'key1': [2]}
It could be used in for-loops etc:

>>> test = dict()
>>> nums = [2, 3, 7, 19, 24]
>>> for num in nums:
...     if num % 2:
...         test.setdefault(num, list()).append(num**2)
...
>>> test
{3: [9], 7: [49], 19: [361]}