Python Practice › Dictionary Programs › Program 87
Initialise with default values
Write a Python program to give every name its own copy of a default settings dictionary.
Input
["Virat", "Rohit"], {"sport": "cricket", "salary": 100000}Output
{'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}Approach
- Copy the defaults for each name.
Solution
names = ["Virat", "Rohit"]defaults = {"sport": "cricket", "salary": 100000}players = {name: defaults.copy() for name in names}players["Rohit"]["salary"] = 120000print(players)Output
{'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}Line by line
Line 3
.copy() gives each player an independent dict, so changing Rohit’s salary does not change Virat’s.
Watch out
dict.fromkeys(names, defaults) would share one dict between all names.
Learn the concept
New to this topic? Read the lesson, then come back.