Python Dictionary fromkeys() Method

Python 字典Python Dictionary


Description

The Python dictionary fromkeys() function is used to create a new dictionary, taking the sequenceseqelements in [the sequence] as the keys of the dictionary,valueand [value] as the initial value corresponding to all keys of the dictionary.

Syntax

fromkeys() method syntax:

dict.fromkeys(seq[, value])

Parameters

  • seq -- List of dictionary keys.
  • value -- Optional parameter, sets the value of the key sequence (seq), defaults to None.

Return Value

This method returns a new dictionary.

Example

The following example demonstrates the usage of the fromkeys() function:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- seq = ('Google', 'Example', 'Taobao') # Do not specify the default key value, defaults to None thisdict = dict.fromkeys(seq) print ("New dictionary is : %s" % str(thisdict)) # Specify the 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, 'Example': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Example': 10}

Python 字典Python Dictionary

Other Extensions