python - 如何从列表中创建多个键,每个键都分配给一个唯一的数组?
问题描述
我的目标是用 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] = []
它做同样的事情。
推荐阅读
- java - 在内部类中的私有类中调用私有方法
- macos - Terratest 在 Mac 上找不到 terraform
- python - 打印数组的对应值
- php - 使用 PHP 输出缓冲区替换 HTML 元素非常慢
- python - pd.to_datetime - 用什么填充缺失值
- angular - Angular 中的 D3.js 拖动
- excel - 当 VBA 错误处理程序导致错误时该怎么办?
- html - 如何在每个单独的 img 标签下放置标签
- php - C 中的 PHP 扩展:_SERVER 在 RINIT 函数中为 NULL
- javascript - Javascript - get element id by inner text