Initialise with default values
Write a Python program to give every name its own copy of a default settings dictionary.
["Virat", "Rohit"], {"sport": "cricket", "salary": 100000}{'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){'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}Line by line
.copy() gives each player an independent dict, so changing Rohit’s salary does not change Virat’s.
dict.fromkeys(names, defaults) would share one dict between all names.
Learn the concept
New to this topic? Read the lesson, then come back.