Post

Python Dictionary fromkeys()

The fromkeys() method returns a new dictionary with the specified keys with specified value.

Python Dictionary fromkeys()

The syntax of fromkeys() is:

1
2
dictionary.fromkeys(key, value)

fromkeys() Parameters

The fromkeys() method takes two parameters as arguments.

  • key - an iterable or collection of items which specify the keys of the new dictionary.
  • value (Optional) - The Values which are going to be assigned to all the elements of the dictionary. Default is None.

Example 1 : How to use fromkeys() method in a python dictionary?

1
2
3
4
5
keys ={ 1,2,3,4}

results = dict.fromkeys(keys)
print(results)

Output:

1
{1: None, 2: None, 3: None, 4: None}

Example 2: How to use fromkeys() method with values in python dictionary?

1
2
3
4
5
6
keys ={'BWM','TOYOTA','AUDI'}
value = 'cars'

results = dict.fromkeys(keys, value)
print(results)

Output:

1
2
{'BWM': 'cars', 'AUDI': 'cars', 'TOYOTA': 'cars'}

Khushal Jethava
Khushal Jethava

Machine Learning Engineer at Codiste, specializing in Generative AI, NLP, and Computer Vision. Building production AI systems with Python.

This post is licensed under CC BY 4.0 by the author.