Python 如何从列表中创建多个键,并将每个键指定给唯一的数组?

Python 如何从列表中创建多个键,并将每个键指定给唯一的数组?,python,Python,我的目标是用Python构建一个字典。我的代码似乎有效。但是,当我尝试将值附加到单个键时,该值将附加到多个键。我理解这是因为fromkeys方法将多个键分配给同一个列表。如何从列表中创建多个键,并将每个键指定给唯一的数组 #Create an Array with future dictionary keys
x = ('key1', 'key2', 'key3')
 #Create a Dictionary from the array
 myDict = dict.fromkeys(x,[]

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

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

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

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

这也有同样的作用。

根据目前为止的答案,我拼凑出了一种有效的方法。这是“python”还是“python最优”的方法

#Create an Array with future dictionary keys
x = ('key1', 'key2', 'key3')


#Create a Dictionary from the array

tempDict = dict.fromkeys(x,[])


myDict = {}



for key in tempDict.keys():
    
    print(key)
    
    myDict[key] = []


#Add some new Dictionary Keys

myDict['TOTAL'] = []

myDict['EVENT'] = []

print(myDict)


#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 x keys.
myDict['key1'].append('Entry') 
print(myDict)

#{'key1': ['Entry'], 'key2': [], 'key3': [], 'TOTAL': ['TOTAL'], 'EVENT':
# []}

你混淆了参考和价值。这些字典键中的每一个都指向同一个列表
myDict=dict.fromkeys([(key,[])表示输入x])
这是否回答了您的问题?我知道你在说什么,我很感激。如何创建字典,使每个关键点都指向一个唯一的列表?我想你已经有了。我如何创建字典,使每个键都引用一个唯一的列表?@MatthewDavidJankowski请看我对你问题的评论。是的,贾里德·史密斯首先回答了这个问题。如果你是新来的(像我一样),列表理解可能很难解析。我将用“长”版本编辑我的答案。我将稍等片刻,看看是否有人有更优雅的方式来做我需要做的事情。如果没有人回答,我会接受这个答案。你的回答确实帮了我不少忙。谢谢在下面的答案中,您不需要tempdict步骤。您不必使用fromkeys创建dict。您可以使用字符串指定一个键
myDict['key1']=[]
将创建该键,并为其分配一个空列表作为值。另外,我不能完全从你的问题中分辨出来,但你知道你不必在字典值中有一个列表,对吗
myDict['total']=1000
也可以工作。当然,如果您知道这一点,但只是想将所有内容都放在嵌套列表中供此使用,请随意忽略。