python中dict的fromkeys用法

fromkeys是创造一个新的字典。就是事先造好一个空字典和一个列表,fromkeys会接收两个参数,第一个参数为从外部传入的可迭代对象,会将循环取出元素作为字典的key值,另外一个参数是字典的value值,不写所有的key值所对应的value值均为None,写了则为默认的值

fromkeys() 方法语法

      dict.fromkeys(seq[, value])

  seq -- 字典键值列表。

  value -- 可选参数, 设置键序列(seq)对应的值,默认为 None。

先看个简单的实例:

1 v = dict.fromkeys(range(10))
2 print(v)
3 
4 结果:
5 {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}

传入第二个参数:

1 v = dict.fromkeys(range(10),'hello')
2 print(v)
3 
4 结果:
5 {0: 'hello', 1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello', 5: 'hello', 6: 'hello', 7: 'hello', 8: 'hello', 9: 'hello'}

再看一个实例:

 1 # dict.fromkeys(seq[, value])
 2 seq = ('name', 'age', 'class')
 3 
 4 # 不指定值
 5 dict = dict.fromkeys(seq)
 6 print("新的字典为 : %s" % str(dict))
 7 
 8 # 赋值 10
 9 dict = dict.fromkeys(seq, 10)
10 print("新的字典为 : %s" % str(dict)) 
11 >>新的字典为 : {'age': None, 'name': None, 'class': None}
12 
13 # 赋值一个元组
14 dict = dict.fromkeys(seq,('zs',8,'Two'))
15 print("新的字典为 : %s" % str(dict))
16 >>新的字典为 : {'age': ('zs', 8, 'Two'), 'name': ('zs', 8, 'Two'), 'class': ('zs', 8, 'Two')}
原文地址:https://www.cnblogs.com/gide/p/12286480.html