add value in dict python code example
Example 1: 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 2: add value to dictionary python
dict[key] = value
Example 3: adding one element in dictionary python
mydict = {'score1': 41,'score2': 23}
mydict['score3'] = 45
print(mydict)
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}
Example 5: python dictoinary add value
student_scores = {'Simon': 45 }
print(student_scores)
student_scores['Sara'] = 63
print(student_scores)