logo

Python Dictionary Fromkeys() Method


Show

Description

Python dictionary method fromkeys() generates a new dictionary with inputs from seq and prices set to cost. Python Dictionary fromKeys() is an integral purpose that produces a new vocabulary from the known succession of components with a charge offered by the client. The fromkeys process revisits the dictionary with particular keys and costs. The fromkeys() assists us to reach this extreme task with easiness and utilize just a solitary method.

Syntax

Following is the syntax for fromkeys() method:

dict.fromkeys(seq[, value])

Parameters

  • seq - This is the list of values which would be used for dictionary keys preparation.
  • value - This is optional, if provided then value would be set to this value

Return Value

This method returns the list.

Example

The following example shows the usage of fromkeys() method

#!/usr/bin/python

seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" %  str(dict)

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

When we run the above program, it produces the following result

New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.