Python 为什么嵌套字典不能正确追加到列表中?
我试图将字典附加到列表中,但我发现子字典总是保留我从CSV文件(deviceProfile.CSV)读取的最后一个字典。有人知道为什么吗? 这是我的CSV文件Python 为什么嵌套字典不能正确追加到列表中?,python,list,dictionary,append,Python,List,Dictionary,Append,我试图将字典附加到列表中,但我发现子字典总是保留我从CSV文件(deviceProfile.CSV)读取的最后一个字典。有人知道为什么吗? 这是我的CSV文件 name,description,primaryTable,startingAddress,boolIndex test_name_1,1,table_1,1,1 test_name_2,2,table_2,2,2 test_name_3,3,table_3,3,3 这是我的python代码 import csv import yaml
name,description,primaryTable,startingAddress,boolIndex
test_name_1,1,table_1,1,1
test_name_2,2,table_2,2,2
test_name_3,3,table_3,3,3
这是我的python代码
import csv
import yaml
from pprint import pprint
resource = {
'name': "",
'description': "",
'attributes':
{ 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}
resourceArray = []
with open("deviceProfile.csv") as f:
myCsvDic = csv.DictReader(f)
for row in myCsvDic:
resource['name'] = row['name']
resource['description'] = row['description']
resource['attributes']['primaryTable'] = row['primaryTable']
resource['attributes']['startingAddress'] = row['startingAddress']
resource['attributes']['boolIndex'] = row['boolIndex']
test = resource.copy()
resourceArray.append(test)
pprint (resourceArray)
结果是
[{'attributes': {'boolIndex': '3',
'primaryTable': 'table_3',
'startingAddress': '3'},
'description': '1',
'name': 'test_name_1'},
{'attributes': {'boolIndex': '3',
'primaryTable': 'table_3',
'startingAddress': '3'},
'description': '2',
'name': 'test_name_2'},
{'attributes': {'boolIndex': '3',
'primaryTable': 'table_3',
'startingAddress': '3'},
'description': '3',
'name': 'test_name_3'}]
奇怪的是,名称和描述被正确地添加到列表中,但是属性。属性始终附加到最后一个子字典
任何帮助都将不胜感激。谢谢。这是因为
copy
。默认情况下,“复制”是“浅层复制”,它将仅复制级别1的元素。
您应该在您的案例中使用deepcopy
。将test=resource.copy()
替换为:
from copy import deepcopy
test = deepcopy(resource)
查看此链接以获取更多信息,或任何其他链接,这些链接告诉您有关
复制(浅层和深层)
为什么在循环之外的顶部有资源
resource = {
'name': "",
'description': "",
'attributes':
{ 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}
删除该选项,然后将循环更改为:
for row in myCsvDic:
resource = {}
resource['name'] = row['name']
resource['description'] = row['description']
resource['attributes']['primaryTable'] = row['primaryTable']
resource['attributes']['startingAddress'] = row['startingAddress']
resource['attributes']['boolIndex'] = row['boolIndex']
resourceArray.append(resource)