当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python dict fromkeys()用法及代码示例


有时需要根据给定的键生成字典。蛮力地执行它会花费时间,并且会变得更加乏味。因此,fromkeys()仅使用一种方法即可帮助我们轻松完成此任务。本文介绍了与此函数相关的工作和其他方面。

用法:fromkeys(seq, val)

参数:
seq:要转换为字典的序列。
val:需要分配给生成的键的初始值。默认为无。


返回:如果没有提供值,则字典的键映射到“无”,否则映射到字段中提供的值。

代码1:演示fromkeys()的工作

# Python 3 code to demonstrate  
# working of fromkeys() 
  
# initializing sequence  
seq = { 'a', 'b', 'c', 'd', 'e' } 
  
# using fromkeys() to convert sequence to dict  
# initializing with None 
res_dict = dict.fromkeys(seq) 
  
# Printing created dict 
print ("The newly created dict with None values:" + str(res_dict)) 
  
  
# using fromkeys() to convert sequence to dict  
# initializing with 1 
res_dict2 = dict.fromkeys(seq, 1) 
  
# Printing created dict 
print ("The newly created dict with 1 as value:" + str(res_dict2))

输出:

The newly created dict with None values:{‘d’:None, ‘a’:None, ‘b’:None, ‘c’:None, ‘e’:None}
The newly created dict with 1 as value:{‘d’:1, ‘a’:1, ‘b’:1, ‘c’:1, ‘e’:1}

fromdict()以可变对象作为值的行为:

fromdict()也可以随默认对象一起提供。但是在这种情况下,字典会构成一个深层副本,即如果我们在原始列表中附加值,则附加会在键的所有值中进行。

预防措施:某些词典理解技术可用于创建新列表作为键值,而不将原始列表指向键值。

代码2:演示可变对象的行为。

# Python 3 code to demonstrate  
# behaviour with mutable objects 
  
# initializing sequence and list 
seq = { 'a', 'b', 'c', 'd', 'e' } 
lis1 = [ 2, 3 ] 
  
# using fromkeys() to convert sequence to dict 
# using conventional method 
res_dict = dict.fromkeys(seq, lis1) 
  
# Printing created dict 
print ("The newly created dict with list values:"
                                    + str(res_dict)) 
  
# appending to lis1 
lis1.append(4) 
  
# Printing dict after appending 
# Notice that append takes place in all values 
print ("The dict with list values after appending:"
                                    + str(res_dict)) 
  
lis1 = [ 2, 3 ] 
print ('\n') 
  
# using fromkeys() to convert sequence to dict 
# using dict. comprehension 
res_dict2 = { key:list(lis1) for key in seq } 
  
# Printing created dict 
print ("The newly created dict with list values:" 
                                  + str(res_dict2)) 
  
# appending to lis1 
lis1.append(4) 
  
# Printing dict after appending 
# Notice that append doesnt take place now. 
print ("The dict with list values after appending (no change):"
                                               + str(res_dict2))

输出:

The newly created dict with list values:{‘d’:[2, 3], ‘e’:[2, 3], ‘c’:[2, 3], ‘a’:[2, 3], ‘b’:[2, 3]}
The dict with list values after appending:{‘d’:[2, 3, 4], ‘e’:[2, 3, 4], ‘c’:[2, 3, 4], ‘a’:[2, 3, 4], ‘b’:[2, 3, 4]}

The newly created dict with list values:{‘d’:[2, 3], ‘e’:[2, 3], ‘c’:[2, 3], ‘a’:[2, 3], ‘b’:[2, 3]}
The dict with list values after appending (no change):{‘d’:[2, 3], ‘e’:[2, 3], ‘c’:[2, 3], ‘a’:[2, 3], ‘b’:[2, 3]}



相关用法


注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python Dictionary | fromkeys() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。