[英]How do I create multiple keys from a list with each key assigned to a unique array?
My goal is to build a dictionary in Python.我的目标是在 Python 中建立一个字典。 My code seems to work.我的代码似乎有效。 However, when I attempt to append a value to a single key the value is appended to multiple keys.但是,当我尝试将 append 值添加到单个键时,该值将附加到多个键。 I understand this is because the fromkeys method assigns multiple keys to the same list.我理解这是因为 fromkeys 方法将多个键分配给同一个列表。 How do I create multiple keys from a list with each assigned to a unique array?如何从列表中创建多个键,每个键都分配给一个唯一的数组?
#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, and key3 all contain a reference to a single list, which you are appending to. Key1、key2 和 key3 都包含对您要附加到的单个列表的引用。 They don't each include a unique list.它们并不都包含一个唯一的列表。
Jared's answer above is correct.上面贾里德的回答是正确的。 You can also write:你也可以写:
myDict = dict()
for key in x:
myDict[key] = []
which does the same thing.它做同样的事情。
Based on the answers so far I cobbled together an approach that works.根据迄今为止的答案,我拼凑了一种可行的方法。 Is this the 'python' or 'python optimal' way to do this?这是执行此操作的“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':
# []}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.