How to insert key-value pair into dictionary at a specified position?

Had the same issue and solved this as described below without any additional imports being required and only a few lines of code.
Tested with Python 3.6.9.

  1. Get position of key ‘Age’ because the new key value pair should get inserted before
  2. Get dictionary as list of key value pairs
  3. Insert new key value pair at specific position
  4. Create dictionary from list of key value pairs
mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(mydict)
# {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

pos = list(mydict.keys()).index('Age')
items = list(mydict.items())
items.insert(pos, ('Phone', '123-456-7890'))
mydict = dict(items)

print(mydict)
# {'Name': 'Zara', 'Phone': '123-456-7890', 'Age': 7, 'Class': 'First'}

Edit 2021-12-20:
Just saw that there is an insert method available ruamel.yaml, see the example from the project page:

import sys
from ruamel.yaml import YAML

yaml_str = """\
first_name: Art
occupation: Architect  # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""

yaml = YAML()
data = yaml.load(yaml_str)
data.insert(1, 'last name', 'Vandelay', comment="new key")
yaml.dump(data, sys.stdout)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)