Insert a key at the beginning

EasyDictionary Programs · 21 of 94

Write a Python program to insert a key at the beginning of a dictionary.

Advertisement
Input
{"course": "python", "institute": "sqatools"}, insert ("name", "omkar")
Output
{'name': 'omkar', 'course': 'python', 'institute': 'sqatools'}

Approach

  1. Dicts keep insertion order, so build a new dict with the new key first.

Solution

Python
d = {"course": "python", "institute": "sqatools"}d = {"name": "omkar", **d}print(d)
Output
{'name': 'omkar', 'course': 'python', 'institute': 'sqatools'}

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs