add key value to dictionary python code example

Example 1: add new keys to a dictionary python

d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}

Example 2: python create dictionary from key value

>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = dict(zip(L1,L2))
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Example 3: python dictionary add key-value pair

dict = {'key1':'value_one', 'key2':'value_two'}  
dict['key3'] = 'value_three'

Example 4: add value to dictionary python

dict[key] = value

Example 5: python append to dictionary

dict = {1 : 'one', 2 : 'two'}
# Print out the dict
print(dict)
# Add something to it
dict[3] = 'three'
# Print it out to see it has changed
print(dict)

Example 6: append dictionary python

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}