Home » Python

Python Dictionary fromkeys() Method with Example

Python Dictionary fromkeys() Method: Here, we are going to learn about the fromkeys() method in Python with example.
Submitted by IncludeHelp, on November 25, 2019

Dictionary fromkeys() Method

fromkeys() method is used to create a dictionary with given keys and value.

Syntax:

    dictionary_name.fromkeys(keys, value)

Parameter(s):

  • keys – It represents a container (iterable) with keys.
  • value – It is an optional parameter, that is used to specify the value. The default value of None.

Return value:

The return type of this method is <class 'dict'>, it returns the newly created dictionary with specified keys and values.

Example:

# Python Dictionary fromkeys() Method with Example

# keys iterbale
keys = ('id', 'age', 'perc')

# value
value = 0

# creating dictionary with keys and value
x = dict.fromkeys(keys, value)

# printing dictionary
print("data of x dictionary...")
print(x)

# creating dictionary with keys only
y = dict.fromkeys(keys)

# printing dictionary
print("data of y dictionary...")
print(y)

Output

data of x dictionary...
{'perc': 0, 'id': 0, 'age': 0}
data of y dictionary...
{'perc': None, 'id': None, 'age': None}






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.