Python 从嵌套字典中删除所有出现的值
我有一个嵌套字典,如下所示Python 从嵌套字典中删除所有出现的值,python,dictionary,Python,Dictionary,我有一个嵌套字典,如下所示 myDict= { "id": 10, "state": "MY LIST", "Stars": { "BookA": { "id": 10, "state": "new book", "Mystery": {
myDict= {
"id": 10,
"state": "MY LIST",
"Stars":
{
"BookA": {
"id": 10,
"state": "new book",
"Mystery": {
"AuthorA":
{
"id": "100",
"state": "thriller"
},
"AuthorB":
{
"id": "112",
"state": "horror"
}
},
"Thriller": {
"Store1":
{
"id": "300",
"state": "Old"
}
}
}
}
}
我想返回一个删除了所有“状态”:“文本”的字典。这意味着,我想删除所有的“state”字段,并有如下输出。
我希望它是通用方法,因为字典可以嵌套在多个级别上。
myDict=
{
id: 10,
"Stars":
{
"BookA": {
"id": 10
"Mystery": {
"AuthorA":
{
"id": "100"
},
"AuthorB":
{
"id": "112"
}
},
"Thriller": {
"Store1":
{
"id": "300"
}
}
}
}
我尝试了以下方法,但似乎不起作用。它只删除“状态”:“我的列表”。有人能帮我解决这个问题吗
def get(self):
removelist= ["state"]
new_dict = {}
for key, item in myDict.items():
if key not in removelist:
new_dict.update({key: item})
return new_dict
它不会删除所有的“状态”值。问题是您没有处理嵌套字典
def get(self):
removelist= ["state"]
new_dict = {}
for key, item in myDict.items():
if key not in removelist:
new_dict.update({key: item})
if isinstance(item, dict):
# You'll need to handle this use case.
return new_dict
为了详细说明,让我们回顾一下您的词典:
myDict= {
"id": 10, # int
"state": "MY LIST", # string
"Stars": { # dictionary
"BookA": {
"id": 10, # int
"state": "new book", # string
"Mystery": { # dictionary
"AuthorA": {
"id": "100",
"state": "thriller"
},
"AuthorB": {
"id": "112",
"state": "horror"
}
},
"Thriller": {
"Store1": {
"id": "300",
"state": "Old"
}
}
}
}
}
为了清晰起见,我在类型中添加了注释。您的代码当前正在解析myDict并忽略键“state”。一旦你点击了“Stars”值,你需要解析该字典来忽略键“state”。你可以使用:
其思想是递归地从子树中移除键:对于每个嵌套dict的子树,使用dict理解返回一个没有要移除键的dict;对于每个叶(即单个值),只需返回值
测试:
输出:
{'Stars': {'BookA': {'Mystery': {'AuthorA': {'id': '100'},
'AuthorB': {'id': '112'}},
'Thriller': {'Store1': {'id': '300'}},
'id': 10}},
'id': 10}
我不明白你的意思。请您详细说明,我对python非常陌生,非常感谢您的帮助。我详细说明了答案。您需要使用附加代码处理嵌套字典。感谢您的澄清。:)非常感谢你。它起作用了!!这就是清楚的解释。
from pprint import pprint
pprint(remove_keys(myDict, ['state']))
{'Stars': {'BookA': {'Mystery': {'AuthorA': {'id': '100'},
'AuthorB': {'id': '112'}},
'Thriller': {'Store1': {'id': '300'}},
'id': 10}},
'id': 10}