Nelson Guaman Leiva Nelson Guaman Leiva - 7 months ago 11
Python Question

transform php code to python - append new values to the same key in dict

The only way that I know how to do this, is with php but I want to get the same result in python.

PHP Code:

<?php
$array = array();
$array['value1'][] = 'new value 1';
$array['value1'][] = 'new value 2';
?>


I have this code.

array = dict()
array['value 1'] = 'new value 1'
#array['value 1'].append('new value 2') - Error - only works with list


How I can do this?
Regards.

Answer
my_dict = {}
my_dict['value1'] = ['new value 1']
my_dict['value1'] += ['new value 2', 'new value 3']

The first line initializes the dictionary, the second initializes my_dict['value1'] to a list containing one element, and the last line adds two elements to this list. Notice the +=.

Note: you need to use another method if you don't know whether the key 'value1' already exists in the dict (thanks SirParselot). Use this if you don't know if it exists:

my_dict['value2'] = my_dict.get('value2', []) + ['new value 4', 'new value 5']