Use the fromkeys () method for dictionary operations in Python
This article mainly introduces how to use the fromkeys () method for dictionary operations in Python. It is the basic knowledge for getting started with Python. For more information, see
The fromkeys () method sets the sequence key and value to create a new dictionary.
Syntax
The syntax of the fromkeys () method is as follows:
?
1 |
Dict. fromkeys (seq [, value]) |
Parameters
Seq -- this is a list of values that will be used for dictionary key preparation.
Value -- this is optional. If it is provided, the value is set to this value.
Return Value
This method returns a list.
Example
The following example shows how to use the fromkeys () method.
?
1 2 3 4 5 6 7 8 9 |
#! /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 will produce the following results:
?
1 2 |
New Dictionary: {'age': None, 'name': None, 'sex': None} New Dictionary: {'age': 10, 'name': 10, 'sex': 10} |