【问题标题】:How to add a new key pair in list of dict without modifying actual list of dict?如何在不修改实际字典列表的情况下在字典列表中添加新的密钥对?
【发布时间】:2019-12-16 19:04:01
【问题描述】:

我有一个 dict commandsInWord 列表。我正在尝试通过在字典中搜索命令名称来过滤此列表。它给了我一个命令列表commandinWordExists,其中存在命令。以下是我的代码:

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


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

这里的问题是,当我尝试在 dict commandinWordExists 的列表中添加一个新的键/值对 Count 时,这对也会添加到我的实际 dict commandsInWord 列表中。我不希望它被添加到实际列表中。 例如,如果我的commandsInWord dict 列表是:

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

那么如果在这个dict列表中寻找'setzen',那么commandinWordExists的值就是

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

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

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

怎么做才能不修改 dict 的原始列表?

【问题讨论】:

  • 我很难理解你的问题。您能否更好地解释问题是什么?您能否也添加一个输入和所需输出的示例?
  • @alec_djinn 添加了一个示例

标签: python python-3.x list dictionary filter


【解决方案1】:

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

例如:

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

【讨论】:

    【解决方案2】:

    肯定read this

    Python 从不隐式复制任何内容,因此过滤列表中的字典与“原始”列表中的字典相同:

    >>> original = [{"foo": "bar"}]
    >>> filtered = [item for item in original]
    >>> print(id(original[0]))
    140326431879528
    >>> print(id(filtered[0]))
    140326431879528
    >>> original[0] is filtered[0]
    True
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2019-10-06
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2020-04-08
      • 1970-01-01
      相关资源
      最近更新 更多