Initialise with default values

EasyDictionary Programs · 87 of 94

Write a Python program to give every name its own copy of a default settings dictionary.

Advertisement
Input
["Virat", "Rohit"], {"sport": "cricket", "salary": 100000}
Output
{'Virat': {'sport': 'cricket', 'salary': 100000}, 'Rohit': {'sport': 'cricket', 'salary': 120000}}

Approach

  1. Copy the defaults for each name.

Solution

Python
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.

Advertisement

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs