gpt4 book ai didi

python - 如何在字典列表中添加新的 key 对而不修改实际的字典列表?

转载 作者:行者123 更新时间:2023-12-01 06:43:13 25 4
gpt4 key购买 nike

我有一个字典 commandsInWord 列表。我试图通过在字典中搜索命令名称来过滤此列表。它为我提供了命令存在的字典 commandinWordExists 列表。下面是我的代码:

commandinWordExists = list(filter(lambda commandInWord: commandInWord['Name'] == command, commandsInWord))


if commandinWordExists:
commandinWordExists[0]['Count'] = commandsInModule[command]

这里的问题是,当我尝试在字典 commandinWordExists 列表中添加新的键/值对 Count 时,该对也会添加到我的实际列表中字典commandsInWord。我不希望将其添加到实际列表中。例如,如果我的 commandsInWord 字典列表是:

[{'Ability':'Green'
'Name':'setzen'
'Status':'freigegeben'}]

然后,如果在此字典列表中查找'setzen',则commandinWordExists值将为

[{'Ability':'Green'
'Name':'setzen'
'Status':'freigegeben'}]

现在,如果在 dict commandinWordExists 列表中添加一个新的键/值对 Count ,那么它也会修改 dict commandsInWord 的原始列表。现在两个字典列表都将具有以下值:

[{'Ability':'Green'
'Name':'setzen'
'Count' : 27
'Status':'freigegeben'}]

如何才能使原始字典列表不被修改?

最佳答案

如果我理解正确,您需要创建列表的副本。

例如:

import copy
commandinWordExists = list(filter(lambda commandInWord: commandInWord['Name'] == command, copy.deepcopy(commandsInWord)))

关于python - 如何在字典列表中添加新的 key 对而不修改实际的字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59355024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com