dictrionary python code example
Example: 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'})