Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Dictionary fromkeys() Method

Python3 Dictionary fromkeys() Method

Python3 Dictionaries Python3 Dictionary


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

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

)

print

(

"

The new dictionary is: %s

"

%

str

(

tinydict

)

)

tinydict

=

dict

.

fromkeys

(

seq

,

10

)

print

(

"

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

)

print

(

thisdict

)

The output of the above example is:


{'key1': None, 'key2': None, 'key3': None}

Python3 Dictionaries Python3 Dictionary