Python Dictionary fromkeys() method
Description
The Python dictionary fromkeys() function creates a new dictionary, using the elements of sequence seq as keys and value as the initial value for all keys.
Syntax
fromkeys() method syntax:
dict.fromkeys(seq[, value])
Parameters
- seq -- a list of dictionary keys.
- value -- optional parameter that sets the value for the key sequence (seq), defaulting to None.
Return Value
This method returns a new dictionary.
Example
The following example shows how to use the fromkeys() function:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
seq
=
(
'
'
,
'
Runoob
'
,
'
Taobao
'
)
Without specifying a default key value, it defaults to None
thisdict
=
dict
.
fromkeys
(
seq
)
(
"
New dictionary is: %s
"
%
str
(
thisdict
)
)
Specify a default key value
thisdict
=
dict
.
fromkeys
(
seq
,
10
)
(
"
New dictionary is: %s
"
%
str
(
thisdict
)
)
The output of the above example is:
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
Python Dictionary