Reputation: 1913
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. E.g.:
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?
Upvotes: 2
Views: 59
Reputation: 82929
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}
Upvotes: 3