Click for All Topics
.
fromkeys()
method is convenient for creating dictionaries where you want to initialize multiple keys with the same default value. It is especially useful when you want to set default values for keys without having to iterate through them individually.
Syntax –
dict.fromkeys(keys, value)
Parameters –
Example 1-
# Using fromkeys() to create a dictionary with default values
keys_list = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys_list, default_value)
print("New Dictionary:", new_dict)
# Output -
# New Dictionary: {'a': 0, 'b': 0, 'c': 0}
In the above example –
.
fromkeys()
method to create a new dictionary (new_dict
) with keys specified in the keys_list
and a default value of 0
.keys_list
is present in the dictionary with the specified default value.
Example 2- Initializing with Numeric Keys
# Using fromkeys() to create a dictionary with numeric keys
numeric_keys = range(1, 4)
default_value = 'default'
numeric_dict = dict.fromkeys(numeric_keys, default_value)
print("Numeric Dictionary:", numeric_dict)
# Output -
# Numeric Dictionary: {1: 'default', 2: 'default', 3: 'default'}
Example 3- Initializing with String Keys
# Using fromkeys() to create a dictionary with string keys
string_keys = ['apple', 'banana', 'orange']
default_quantity = 0
fruits_dict = dict.fromkeys(string_keys, default_quantity)
print("Fruits Dictionary:", fruits_dict)
# Output -
# Fruits Dictionary: {'apple': 0, 'banana': 0, 'orange': 0}
Example 4- Initializing with Default Value as a List
# Using fromkeys() to create a dictionary with default value as a list
keys_list = ['x', 'y', 'z']
default_list = []
list_dict = dict.fromkeys(keys_list, default_list)
# Modifying one of the lists
list_dict['x'].append(1)
print("List Dictionary:", list_dict)
# Output -
# List Dictionary: {'x': [1], 'y': [], 'z': []}
Example 5- Initializing with Different Default Values
# Using fromkeys() to create a dictionary with different default values
keys = ['red', 'green', 'blue']
default_values = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
color_dict = dict.fromkeys(keys, default_values)
print("Color Dictionary:", color_dict)
# Output -
# Color Dictionary: {'red': {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'},
# 'green': {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'},
# 'blue': {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}}
Example 6-
# Using fromkeys() to create a dictionary with default value as None
keys_list = ['a', 'b', 'c']
default_dict = dict.fromkeys(keys_list)
print("Default Dictionary:", default_dict)
# Output -
# Default Dictionary: {'a': None, 'b': None, 'c': None}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India