缩短此示例的代码,我对其进行迭代,就好像它有多个键一样。
string = '''
{
"people":
{
"a":
{
"parent":
{
"father": "x"
}
}
}
}
'''
data = json.loads(string)
我确保我的条件有效,它输出“ok”,所以没问题。
for name in data["people"].values():
if name["parent"]["father"] == "x":
print("ok")
然后我修改上面的代码以删除该 key ,但出现以下错误:
类型错误:不可散列的类型:'dict'
for name in data["people"].values():
if name["parent"]["father"] == "x":
del data["people"][name]
我做错了什么?
谢谢
最佳答案
您尝试使用 name
作为键,但 name
实际上是一个字典,而不是字符串。使用 .items()
获取名称和内容:
for name, contents in data["people"].items():
if contents["parent"]["father"] == "x":
del data["people"][name]
但是请注意,这也不起作用。您无法在迭代字典时更改字典的大小。您可以通过调用 list
或类似方法来强制 .items()
完全使用:
for name, contents in list(data["people"].items()):
if contents["parent"]["father"] == "x":
del data["people"][name]
最后,data
将只是 {'people': {}}
,我相信这就是您想要的。
关于python - 无法使用 del 函数删除 json 中的字典键。收到类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54661183/