Fuzzy dict access
At the time I wrote this little snippet I was often working with dictionaries in python and struggling to remember the exact keys that would be required to access the fields I wanted. This is long before starting this blog and was one of the mini-projects that has helped push me to start typing up the side projects and wonderings that I have.
The premise is that you have some idea of the path to the desired element in the dictionary but not all of it. Given a dictionary, this program should return the first object in the dictionary tree which matches that path.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fuzy(obj, path): | |
''' | |
assumptions | |
- The path is in order | |
- Once an element of the path is found it shouldn't be ignored | |
''' | |
if path == []: | |
return obj | |
if path[0] in obj.keys(): | |
return fuzy(obj[path[0]], path[1:]) | |
for k in obj.keys(): | |
v = fuzy(obj[k], path) | |
if v: | |
return v |
Comments
Post a Comment