【问题标题】:Why the nested dictionary cannot append into list correctly?为什么嵌套字典不能正确附加到列表中?
【发布时间】:2020-09-20 20:55:44
【问题描述】:

我尝试将字典附加到列表中,但我发现子字典始终保留我从 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'}]

奇怪的是 namedescription 正确地附加到列表中,但是 attributes属性总是附加到最后一个子字典。

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

【问题讨论】:

    标签: python list dictionary append


    【解决方案1】:

    这是因为copy。默认情况下,复制是浅复制,它只会复制 1 级元素。 你应该在你的情况下使用deepcopy。将test = resource.copy() 替换为:

    from copy import deepcopy
    
    test = deepcopy(resource)
    

    查看此Link 了解更多信息,或任何其他告诉您有关copy(shallow and deep) 的链接。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-07
        • 2021-06-08
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        相关资源
        最近更新 更多