关于python:如何从字典列表中删除k,v条目

How to remove k,v entries from a list of dictionaries

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

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

我已经尝试在适当的位置删除这些值,但得到了"迭代期间字典更改的大小"。

1
2
3
4
5
6
7
8
9
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)


问题3:在Python dict.items()只是一景附注(a copy of the字典的项目-你不能随迭代的变化信息。 </P >

但是你可以把《dict.items()迭代器为A(这list()副本和计算机网络decouples从词典,这条路的),那么你可以反复交叉的copy of the dict.items()吧: </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

输出: </P >

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

更多的在线python2 / python3 dict.items()答案:这是什么是差分之间的dict.items()和()dict.iteritems吗? </P >


请尝试这个。信息技术的使用,因为它fewer iterations设置超时群岛一线,在送他们到流行音乐/解除。也,它只使用Keys(list(DLC)),而不是(键/值的元组。 </P >

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

输出: </P >

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