Easy Tutorial
❮ Python Att Dictionary Copy Python Os Openpty ❯

Python3 Dictionary fromkeys() Method

Python3 Dictionary


Description

The fromkeys() function in Python dictionaries is used to create a new dictionary with keys from a sequence (seq) and values set to a specified value. If no value is provided, the default value for all keys is None.

Syntax

The syntax for the fromkeys() method is:

dict.fromkeys(seq[, value])

Parameters

Return Value

This method returns a new dictionary.

Example

The following example demonstrates the use of the fromkeys() function:

#!/usr/bin/python3

seq = ('name', 'age', 'sex')

tinydict = dict.fromkeys(seq)
print("New dictionary is : %s" % str(tinydict))

tinydict = dict.fromkeys(seq, 10)
print("New dictionary is : %s" % str(tinydict))

Output of the above example:

New dictionary is : {'name': None, 'age': None, 'sex': None}
New dictionary is : {'name': 10, 'age': 10, 'sex': 10}

Without specifying a value:

#!/usr/bin/python3

x = ('key1', 'key2', 'key3')

thisdict = dict.fromkeys(x)

print(thisdict)

Output of the above example:

{'key1': None, 'key2': None, 'key3': None}

Python3 Dictionary

❮ Python Att Dictionary Copy Python Os Openpty ❯