Python3 Dictionary fromkeys() Method

Python3 字典Python3 Dictionary


Description

The Python dictionary fromkeys() function is used to create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and value as the initial value corresponding to all keys of the dictionary.

Syntax

fromkeys() method syntax:

dict.fromkeys(seq[, value])

Parameters

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

Return Value

This method returns a new dictionary.

Example

The following example demonstrates 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 字典Python3 Dictionary

Other Extensions