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

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method

Python Dictionary Python 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 (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

seq

=

(

'

Google

'

,

'

Runoob

'

,

'

Taobao

'

)

Without specifying a default key value, it defaults to None

thisdict

=

dict

.

fromkeys

(

seq

)

print

(

"

New dictionary is: %s

"

%

str

(

thisdict

)

)

Specify a default key value

thisdict

=

dict

.

fromkeys

(

seq

,

10

)

print

(

"

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 Python Dictionary