Python fromkeys() Function

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

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

dOne = dict.fromkeys(k, v)
print(dOne)

dTwo = dict.fromkeys(k)
print(dTwo)

The output will be:

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

Python fromkeys() Function Syntax

The syntax of 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 fromkeys() function in Python.

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

The output will be:

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

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋