如何从字典列表中删除k,v项

2024-10-03 15:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我试着删除现有的值,但得到“dictionary changed size during iteration”。你知道吗

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)

Tags: 文件inidjsonfordatadictionaryitems
2条回答

请试试这个。它使用较少的迭代,因为它首先过滤掉键,然后再将它们发送到pop/remove。而且,它只使用键(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}]}

问题:dict.items()在python3中只是一个视图-不是dict项的副本-您不能在迭代时更改它。你知道吗

但是,您可以将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的更多信息:in this answerWhat is the difference between dict.items() and dict.iteritems()?

相关问题 更多 >