Python fromkeys() function

The fromkeys() function in Python is used to create a dictionary using specified keys and values. For example:

k = ("one", "two", "three")
v = 100

dOne = dict.fromkeys(k, v)

dTwo = dict.fromkeys(k)

The output will be:

{'one': 100, 'two': 100, 'three': 100}
{'one': None, 'two': None, 'three': None}

Python fromkeys() function syntax

The syntax of the fromkeys() function in Python is:

dict.fromkeys(keys, value)

where "keys" refers to an iterable that specifies the keys, whereas "value" refers to a value to set for all the keys.

Note: The first parameter (keys) is required, whereas the second parameter (value) is optional.

Python fromkeys() Function Example

Here is an example of the fromkeys() function in Python.

d = dict.fromkeys([12, 432, 45, 5, 6, 34])

The output will be:

{12: None, 432: None, 45: None, 5: None, 6: None, 34: None}

Advantages of the fromkeys() function in Python

Disadvantages of the fromkeys() function in Python

Python Online Test

« Previous Function Next Function »

Liked this post? Share it!