【发布时间】:2020-08-11 17:13:58
【问题描述】:
我的目标是用 Python 构建一个字典。我的代码似乎有效。但是,当我尝试将值附加到单个键时,该值会附加到多个键。我理解这是因为 fromkeys 方法将多个键分配给同一个列表。如何从一个列表中创建多个键,每个键都分配给一个唯一的数组?
#Create an Array with future dictionary keys
x = ('key1', 'key2', 'key3')
#Create a Dictionary from the array
myDict = dict.fromkeys(x,[])
#Add some new Dictionary Keys
myDict['TOTAL'] = []
myDict['EVENT'] = []
#add an element to the Dictionary works as expected
myDict['TOTAL'].append('TOTAL')
print(myDict)
#{'key1': [], 'key2': [], 'key3': [], 'TOTAL': ['TOTAL'], 'EVENT': []}
#add another element to the Dictionary
#appending data to a key from the x Array sees the data appended to all the keys from the x array
myDict['key1'].append('Entry')
print(myDict)
#{'key1': ['Entry'], 'key2': ['Entry'], 'key3': ['Entry'], 'TOTAL': ['TOTAL'], 'EVENT':
# []}
【问题讨论】:
-
您混淆了参考和价值。这些字典键中的每一个都指向 same 列表。
myDict = dict.fromkeys([(key, []) for key in x]) -
这能回答你的问题吗? Python -- by value vs by reference
-
我明白你在说什么,我很感激。如何创建我的字典,使每个键都指向一个唯一的列表?
标签: python