dict insert code example
Example 1: add new keys to a dictionary python
d = {'key':'value'}
print(d)
d['mynewkey'] = 'mynewvalue'
print(d)
Example 2: python 3.7 insert at place in dict
def insert_item(dic, item={}, pos=None):
"""
Insert a key, value pair into an ordered dictionary.
Insert before the specified position.
"""
from collections import OrderedDict
d = OrderedDict()
if not item or not isinstance(item, dict):
print('Aborting. Argument item must be a dictionary.')
return dic
if not pos:
dic.update(item)
return dic
for item_k, item_v in item.items():
for k, v in dic.items():
if k == pos:
d[item_k] = item_v
d[k] = v
return d
d = {'A':'letter A', 'C': 'letter C'}
insert_item(['A', 'C'], item={'B'})
insert_item(d, item={'B': 'letter B'})
insert_item(d, pos='C', item={'B': 'letter B'})
Example 3: add value to dictionary python
dict[key] = value
Example 4: python how to add a new key to a dictionary
dictionary['new_key'] = value
d = {'a': 1, 'b': 5}
d['c'] = 37
print(d)
--> {'a': 1, 'b': 5, 'c': 37}