목록에 사전을 추가하려고하는데 하위 사전은 항상 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
다음은 내 파이썬 코드입니다.
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'}]
이름 과 설명 이 목록에 올바르게 추가되는 것이 이상 하지만 attributes . 속성은 항상 마지막 하위 사전을 추가한다.
어떤 도움을 주시면 감사하겠습니다. 감사.
이것은 copy
. 기본적으로 복사는 얕은 복사이며 레벨 1 요소 만 복사합니다. deepcopy
귀하의 경우에 사용해야 합니다. 다음으로 교체 test = resource.copy()
:
from copy import deepcopy
test = deepcopy(resource)
자세한 내용 은이 링크 또는에 대해 알려주는 다른 링크를 참조하십시오 copy(shallow and deep)
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다