我在我的一个项目中使用 kendoUI Grid。我使用他们的 api 检索了一段数据,发现它在我的 json/dictionary 中添加了一些“不需要的”数据。将 json 传递回我的 Pyramid 后端后,我需要删除这些键。问题是,字典可以是任何深度,而我事先不知道深度。
例子:
product = {
id: "PR_12"
name: "Blue shirt",
description: "Flowery shirt for boys above 2 years old",
_event: {<some unwanted data here>},
length: <some unwanted data>,
items: [{_event: {<some rubbish data>}, length: <more rubbish>, price: 23.30, quantity: 34, color: "Red", size: "Large"}, {_event: {<some more rubbish data>}, length: <even more rubbish>, price: 34.50, quantity: 20, color: "Blue", size: "Large"} ....]
}
我想特别删除两个键:“_event”和“length”。我尝试编写一个递归函数来删除数据,但我似乎无法正确处理。有人可以帮忙吗?
这是我所拥有的:
def remove_specific_key(the_dict, rubbish):
for key in the_dict:
if key == rubbish:
the_dict.pop(key)
else:
# check for rubbish in sub dict
if isinstance(the_dict[key], dict):
remove_specific_key(the_dict[key], rubbish)
# check for existence of rubbish in lists
elif isinstance(the_dict[key], list):
for item in the_dict[key]:
if item == rubbish:
the_dict[key].remove(item)
return the_dict