首页 > 解决方案 > 如何从列表中创建多个键,每个键都分配给一个唯一的数组?

问题描述

我的目标是用 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':
# []}

标签: python

解决方案


Key1、key2 和 key3 都包含对您要附加到的单个列表的引用。它们并不都包含一个唯一的列表。

上面贾里德的回答是正确的。你也可以写:

myDict = dict()
for key in x:
  myDict[key] = []

它做同样的事情。


推荐阅读