[英]How to get a dictionary and all its elements by key?
I have a structure like this: 我有这样的结构:
{
"content": "Name 1",
"name": "directory",
"decendent": [
{
"content": "Name 2",
"name": "subdirectory",
"decendent": None
},
{
"content": "Name 3",
"name": "subdirectory_two",
"decendent": [
{
"content": "Name 4",
"name": "subsubdirectory",
"decendent": None
}
]
}
]
}
I have to look for the name (name is a string and unique), and if I found it - save the whole dictionary in other variable. 我必须查找名称(名称是一个字符串并且是唯一的),如果找到它,则将整个词典保存在其他变量中。 Eg:
例如:
I'm looking for "subdirectory", i should get: 我正在寻找“子目录”,我应该得到:
{
"content": "Name 2",
"name": "subdirectory",
"decendent": None
}
and save it in the variable. 并将其保存在变量中。
How to perform this search in Python? 如何在Python中执行此搜索?
You can use a recursive function checking the name of the current dictionary, and if that name matches return the dictionary, and otherwise try the "descendants", if any, and return if those have a match. 您可以使用递归函数检查当前词典的名称,如果该名称匹配,则返回该词典,否则尝试“后代”(如果有),如果匹配则返回。
def find_name(d, name):
if d["name"] == name:
return d
for d2 in d["decendent"] or []:
res = find_name(d2, name)
if res:
return res
Example: 例:
>>> dictionary = { your dictionary }
>>> print find_name(dictionary, "subdirectory")
{'content': 'Name 2', 'name': 'subdirectory', 'decendent': None}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.