在Python中操作字典之fromkeys()方法的使用,pythonfromkeys
在Python中操作字典之fromkeys()方法的使用,pythonfromkeys
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}
相关内容
- 在Python中用get()方法获取字典键值的教程,pythonget
- 在Python中用has_key()方法查找键是否存在的教程,python
- Python中使用items()方法返回字典元素对的教程,pythonit
- 在Python中用keys()方法返回字典键的教程,pythonkeys
- 在Python中操作字典之setdefault()方法的使用,pythonsetdef
- python计算时间差的方法,python计算时间差
- 在Python中使用swapCase()方法转换大小写的教程,pythonsw
- python网络编程之数据传输UDP实例分析,pythonudp实例分析
- python中enumerate函数用法实例分析,pythonenumerate
- Python中title()方法的使用简介,pythontitle
评论关闭