我循环使用以下JSON:
"item 1": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
},
"item 2": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
}
我想为每个项目制作一个包含前两个键值{ - 1}},property 1
的字典(即排除property 2
)。下面的代码实现了所需的结果,但只存储了最新的序列:
property 3
如何存储每个for i in JSON:
value 1 = i["value 1"]
value 2 = i["value 2"]
...
JSON = json.dumps({'property 1':value 1,'property 2':value 2...})
return json.loads(JSON)
>> "item 2": {
"property 1": "value 1",
"property 2": "value 2" ...
# returns item 2, but I'd like item 1 also
的输出而不覆盖另一个?
答案 0 :(得分:2)
使用简单的迭代。
<强>实施例强>
data = {"item 1": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
},
"item 2": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
}
}
d = {}
for i in data:
d[i] = {"property 1": data[i]["property 1"], "property 2": data[i]["property 2"]}
print( d )
<强>输出:强>
{'item 2': {'property 1': 'value 1', 'property 2': 'value 2'}, 'item 1': {'property 1': 'value 1', 'property 2': 'value 2'}}
答案 1 :(得分:2)
这是使用items
方法和字典理解的另一个选项:
data = {"item 1": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
},
"item 2": {
"property 1": "value 1",
"property 2": "value 2",
"property 3": "value 3"
}
}
new_data = {}
for index, value in data.items():
new_data.update({index: {k:v for k, v in value.items() if k != "property 3"}})
print(new_data)
<强>输出:强>
{'item 1': {'property 1': 'value 1', 'property 2': 'value 2'},
'item 2': {'property 1': 'value 1', 'property 2': 'value 2'}}