Python dict.fromkeys usage detailed explanation and examples

Python dict.fromkeys Usage Detailed Explanation and Examples

dict.fromkeys(seq, value=None) is a built-in dictionary method in Python. It creates a new dictionary where the keys are from the sequence seq and the value for each key is a copy of value (if the value parameter is provided), or None (if the value parameter is not provided).

Below are three examples using the dict.fromkeys method:

Example 1: Create a dictionary and set the default value of all keys to None.

seq = ['a', 'b', 'c', 'd']
new_dict = dict.fromkeys(seq)
print(new_dict)

Output:

{'a': None, 'b': None, 'c': None, 'd': None}

Example 2: Create a dictionary and set the default value of all keys to a given value.

seq = ['name', 'age', 'gender']
new_dict = dict.fromkeys(seq, 'Unknown')
print(new_dict)

Output:

{'name': 'Unknown', 'age': 'Unknown', 'gender': 'Unknown'}

Example 3: By passing a string as the seq parameter, create a dictionary with each character in the string as a key and set the default value to an empty list.

seq = 'Python'
new_dict = dict.fromkeys(seq, [])
print(new_dict)

Output:

{'P': [], 'y': [], 't': [], 'h': [], 'o': [], 'n': []}

Leave a Reply

Your email address will not be published. Required fields are marked *