有時需要根據給定的鍵生成字典。蠻力地執行它會花費時間,並且會變得更加乏味。因此,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]}
相關用法
- Python dict pop()用法及代碼示例
- Python dict items()用法及代碼示例
- Python dict setdefault()用法及代碼示例
- Python dict update()用法及代碼示例
- Python dict popitem()用法及代碼示例
- Python dict keys()用法及代碼示例
注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python Dictionary | fromkeys() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。