0

我需要一次更新一个嵌套字典。

我有一个 for 循环,其中rows是 NodeList (minidom)

dictKeys 看起来像这样:

dictKeys = {'LastEditDate': {}, 'LastEditorUserId': {}, 'LastActivityDate': {}, 'Id': {}, 'CommentCount': {}, 'ParentId': {}, 'CreationDate': {}, 'Title': {}, 'PostTypeId': {}, 'AnswerCount': {}, 'ClosedDate': {}, 'OwnerUserId': {}, 'ViewCount': {}, 'Body': {}, 'Score': {}, 'AcceptedAnswerId': {}, 'OwnerDisplayName': {}, 'Tags': {}, 'FavoriteCount': {}}

for index,element in enumerate(rows):
    for key in dictKeys.keys():
        dictKeys[key][index] = ""
    for attrName, attrValue in element.attributes.items():
        dictKeys[attrName][index]= attrValue

它们不是在每次迭代中更新每个键值对,而是一次更新。

{'LastEditDate': {0: '11062'}, 'LastEditorUserId': {0: '11062'}, 'LastActivityDate': {0: '11062'}, 'Id': {0: '11062'}, 'CommentCount': {0: '11062'}, 'ParentId': {0: '11062'}, 'CreationDate': {0: '11062'}, 'Title': {0: '11062'}, 'PostTypeId': {0: '11062'}, 'AnswerCount': {0: '11062'}, 'ClosedDate': {0: '11062'}, 'OwnerUserId': {0: '11062'}, 'ViewCount': {0: '11062'}, 'Body': {0: '11062'}, 'Score': {0: '11062'}, 'AcceptedAnswerId': {0: '11062'}, 'OwnerDisplayName': {0: '11062'}, 'Tags': {0: '11062'}, 'FavoriteCount': {0: '11062'}}

{'LastEditDate': {0: '2'}, 'LastEditorUserId': {0: '2'}, 'LastActivityDate': {0: '2'}, 'Id': {0: '2'}, 'CommentCount': {0: '2'}, 'ParentId': {0: '2'}, 'CreationDate': {0: '2'}, 'Title': {0: '2'}, 'PostTypeId': {0: '2'}, 'AnswerCount': {0: '2'}, 'ClosedDate': {0: '2'}, 'OwnerUserId': {0: '2'}, 'ViewCount': {0: '2'}, 'Body': {0: '2'}, 'Score': {0: '2'}, 'AcceptedAnswerId': {0: '2'}, 'OwnerDisplayName': {0: '2'}, 'Tags': {0: '2'}, 'FavoriteCount': {0: '2'}}

我想知道如何正确地做到这一点?

4

1 回答 1

0

如果你有一个空字典

d = {}

并将其用作初始项目值

dictKeys = {'a': d, 'b': d, 'c': d}

d那么仍然存在一个字典,从所有地方引用。

即使您更新单个项目

dictKeys['a'][0] = 'hello'

此更新似乎无处不在。

assert dictKeys == {'a': {0: 'hello'}, 'b': {0: 'hello'}, 'c': {0: 'hello'}}
于 2020-03-28T06:21:41.537 回答