Add elements to a dictionary

EasyDictionary Programs · 1 of 94

Write a Python program to add elements to a dictionary.

Advertisement
Input
{"name": "Asha"}
Output
{'name': 'Asha', 'city': 'Pune', 'age': 29, 'role': 'tester'}

Approach

  1. Assign to a new key, or use update() for several keys.

Solution

Python
person = {"name": "Asha"}person["city"] = "Pune"person.update({"age": 29, "role": "tester"})print(person)
Output
{'name': 'Asha', 'city': 'Pune', 'age': 29, 'role': 'tester'}

Line by line

Line 2

Assigning to a key that does not exist adds it.

Line 3

update adds (or replaces) several keys at once.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment