【问题标题】:How to remove k,v entries from a list of dictionaries如何从字典列表中删除 k,v 条目
【发布时间】:2019-01-21 19:23:41
【问题描述】:

我想从现有的 json 文件中删除我不需要的值:

{ "items": [ { "id": "abcd", "h": 2, "x": 0, "level": 4 }, { "id": "dfgg", "h": 7, "x": 5, "level": 30 } ] }

我已尝试删除适当的值,但得到“迭代期间字典更改大小”。

with open('inventory2.json', 'r') as inf:
    data = json.load(inf)
    inf.close()

    keysiwant = ['x', 'h']
    for dic in data['items']:
        for k, v in dic.items():
            if k not in keysiwant:
                dic.pop(k, None)

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

问题:python 3 中的dict.items() 只是一个 view - 不是字典项目的副本 - 您无法在迭代时更改它。

但是,您可以将 dict.items() 迭代器放入 list() (以这种方式复制它并将其与 dict 解耦) - 然后您可以迭代 dict.items() 的副本:

import json

t = """{ "items": [ { "id": "abcd", "h": 2, "x": 0, "level": 4 }, 
                    { "id": "dfgg", "h": 7, "x": 5, "level": 30 } ] }"""

data = json.loads(t)   # loads is better for SO-examples .. it makes it a mcve
keysiwant = ['x', 'h']
for dic in data['items']:
    for k, v in list(dic.items()):
        if k not in keysiwant:
            dic.pop(k, None)

print(data) 

输出:

{'items': [{'h': 2, 'x': 0}, {'h': 7, 'x': 5}]}

更多关于 python2/python3 dict.items(): in this answerWhat is the difference between dict.items() and dict.iteritems()?

【讨论】:

  • json.loads() 报错,仍然使用 json.load(),否则,成功了,谢谢 :)
  • @Scott json.loads() 是从 string 而不是文件加载 json ;) 因此更适合在 SO 上作为 minimal reproducible example 进行演示
【解决方案2】:

请试试这个。它使用较少的迭代,因为它先过滤掉键,然后再将它们发送到弹出/删除。此外,它仅使用键 (list(dic)) 而不是元组键/值。

import json

t = """{ "items": [ { "id": "abcd", "h": 2, "x": 0, "level": 4 },
                    { "id": "dfgg", "h": 7, "x": 5, "level": 30 } ] }"""

data = json.loads(t)
keysiwant = ["x", "h"]

for dic in data["items"]:
    for k in (k for k in list(dic) if k not in keysiwant):
        dic.pop(k, None)

print(data)

输出:

{'items': [{'h': 2, 'x': 0}, {'h': 7, 'x': 5}]}

【讨论】:

  • 在我进行的几次比较中,工作得同样好,可能稍微快一些。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2013-12-23
  • 1970-01-01
  • 2020-03-24
  • 2020-07-14
  • 2011-02-28
  • 1970-01-01
相关资源
最近更新 更多