Home  >  Article  >  Backend Development  >  在Python中操作字典之fromkeys()方法的使用

在Python中操作字典之fromkeys()方法的使用

WBOY
WBOYOriginal
2016-06-06 11:17:201573browse

 fromkeys()方法从序列键和值设置为value来创建一个新的字典。
语法

以下是fromkeys()方法的语法:

dict.fromkeys(seq[, value]))

参数

  •     seq -- 这是将用于字典的键准备的值的列表。
  •     value -- 这是可选的,如果提供的话则值将被设置为这个值

返回值

此方法返回列表。
例子

下面的例子显示fromkeys()方法的使用。

#!/usr/bin/python

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict)

dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict)

当我们运行上面的程序,它会产生以下结果:

New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn