Python Practice › Dictionary Programs › Program 1
Add elements to a dictionary
Write a Python program to add elements to a dictionary.
Input
{"name": "Asha"}Output
{'name': 'Asha', 'city': 'Pune', 'age': 29, 'role': 'tester'}Approach
- Assign to a new key, or use
update()for several keys.
Solution
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.