Python dictionary Method - fromkeys()

ht‮//:spt‬www.theitroad.com

The fromkeys() method is a built-in dictionary method in Python that creates a new dictionary from a given sequence of keys with a specified value for each key. The fromkeys() method returns a new dictionary with the specified keys and the same value for each key.

Here's the syntax for the fromkeys() method:

new_dict = dict.fromkeys(iterable, value)

Here, iterable is a sequence of keys, and value is the value to be assigned to each key. If value is not specified, the default value is None.

Here's an example:

# create a dictionary from a list of keys with default value None
my_dict = dict.fromkeys(['apple', 'banana', 'cherry'])

# create a dictionary from a tuple of keys with default value 0
my_dict2 = dict.fromkeys(('apple', 'banana', 'cherry'), 0)

# create a dictionary from a string of keys with default value True
my_dict3 = dict.fromkeys('abcd', True)

# print the dictionaries
print(my_dict)
print(my_dict2)
print(my_dict3)

Output:

{'apple': None, 'banana': None, 'cherry': None}
{'apple': 0, 'banana': 0, 'cherry': 0}
{'a': True, 'b': True, 'c': True, 'd': True}

In this example, we create three dictionaries using the fromkeys() method. The first dictionary is created from a list of keys, and the default value is None. The second dictionary is created from a tuple of keys, and the default value is 0. The third dictionary is created from a string of keys, and the default value is True. Note that the fromkeys() method can take any iterable as its first argument, including a list, tuple, string, or even a range object.

The fromkeys() method is useful when you need to create a dictionary with a fixed set of keys and a default value for each key. It can save time when initializing a dictionary with a large number of keys, because you don't need to manually assign a value to each key. However, note that the fromkeys() method sets the same value for each key, so if you need to assign different values to different keys, you will need to use a loop or a dictionary comprehension to create the dictionary.