我已经做了研究,但找不到任何有效的答案
我有以下JSON文件:
{
"Cars": [{
"Manufacturer": "Audi",
"model": "R8",
"price": 50000,
"a": {
"n": "1",
"street": "ABC Street",
"city": "London",
"postcode": "TW1 1AA"
}
},
{
"Manufacturer": "Ford",
"model": "Fiesta",
"price": 10000,
"a": {
"n": 2,
"street": "DEF street",
"town": "London",
"PostCode": "TW2 2AB"
}
},
{
"Manufacturer": "VW",
"model": "Polo",
"price": 5000,
"a": {
"n": "3",
"Street": "GHI Street",
"town": "London",
"postcode": "TW3 3CD"
}
}
]
}
在我的python文件中,要删除JSON元素,我使用以下命令:
deletecar = int(input("Enter price of car to delete: "))
for item in data["Cars"]:
if deletecar == item["price"]:
item.pop("Manufacturer")
item.pop("model")
item.pop("price")
item.pop("a")
with open("testjson.json", 'w') as f:
json.dump(data, f)
运行此操作时,如果删除JSON文件中的第一辆车,我会发现:
{"Cars": [{}, {"Manufacturer": "Ford", ...
如果我现在再次运行我的程序,但我尝试搜索汽车,由于这些空括号,程序将无法工作
那么如何使用Python删除它们呢
提前谢谢
由于它是一个列表,您可以在列表中找到与您的价格输入匹配的索引值。然后从
'Cars'
列表中的值中删除这些元素您需要删除项目本身,这意味着您需要两个步骤:
del
)你不需要“清空”口述,因为那不是你要找的
或者,您可以使用列表理解或
filter
调用创建一个全新的列表,而不包含有问题的项目,例如(注意:这将“删除”所有匹配的项,而不是像代码那样仅删除第一项)
另外,您可能希望在完成处理后保存,而不是在处理过程中保存
相关问题 更多 >
编程相关推荐