Python3 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, the value for the key sequence (seq), defaults to None.
Return Value
This method returns a new dictionary.
Example
The following example shows how to use the fromkeys() function:
Example
#!/usr/bin/python3
seq
=
(
'
name
'
,
'
age
'
,
'
sex
'
)
tinydict
=
dict
.
fromkeys
(
seq
)
(
"
The new dictionary is: %s
"
%
str
(
tinydict
)
)
tinydict
=
dict
.
fromkeys
(
seq
,
10
)
(
"
The new dictionary is: %s
"
%
str
(
tinydict
)
)
The output of the above example is:
新的字典为 : {'age': None, 'name': None, 'sex': None}
新的字典为 : {'age': 10, 'name': 10, 'sex': 10}
Without specifying a value:
Example
#!/usr/bin/python3
x
=
(
'
key1
'
,
'
key2
'
,
'
key3
'
)
thisdict
=
dict
.
fromkeys
(
x
)
(
thisdict
)
The output of the above example is:
{'key1': None, 'key2': None, 'key3': None}
Python3 Dictionary