如何从词典列表中删除k,v个条目

时间:2019-01-21 19:23:42

标签: python python-3.x dictionary

我想从现有的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)

2 个答案:

答案 0 :(得分:3)

问题: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()?

答案 1 :(得分:0)

请尝试这个。它使用的迭代次数较少,因为它先过滤掉关键点,然后再将它们发送到弹出/删除位置。此外,它仅使用键(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}]}