为什么嵌套字典无法正确追加到列表中?

时间:2020-06-02 11:40:18

标签: 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
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'}]

奇怪的是,名称描述被正确地添加到列表中,但是属性属性始终附加在最后一个子词典中。

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

这是因为copy。默认情况下,副本是浅副本,它将仅复制1级元素。 您应使用deepcopy。将test = resource.copy()替换为:

from copy import deepcopy

test = deepcopy(resource)

查看此Link以获得更多信息,或其他任何可以告诉您copy(shallow and deep)的链接。

答案 1 :(得分:0)

为什么在循环外的顶部有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)
相关问题