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
但是你可以把《
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
请尝试这个。信息技术的使用,因为它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}]} |