Join Regular Classroom : Visit ClassroomTech

Python Dictionary – fromkeys() method

It is a method in python that returns a dictionary with particular keys and value provided to the method.

Syntax:
dict.fromkeys(key, value)
dict- is a keyword here and it should not be changed.

Example 1:

# Python code to understand fromkeys() method in dictionary
# www.codewindow.in

s = ("CodeWindow", "India", "News")
t = 1
x = dict.fromkeys(s, t)
print(x)

Output:

{'CodeWindow': 1, 'India': 1, 'News': 1}

Explanation:
Here it returned a dictionary with specified keys and a fixed value for all of them.
Note: If no value is mention then it returns none as all of their value.

Example 2:

# Python code to understand fromkeys() method in dictionary
# www.codewindow.in

s = ("CodeWindow", "code", "INFYTQ")
x = dict.fromkeys(s)
print(x)

Output:

{'CodeWindow': None, 'code': None, 'INFYTQ': None}

Explanation:
Here it returned a dictionary with keys and none as their value since no value was mentioned in the code.


You Missed

Also Checkout