using a list of strings to traverse a dictionary python -
this question has answer here:
i have dictionary in python represents directory structure,
dict = { "file1.java": { "method1": [], "method2": [] }, "dir1": { "file2.java":{ . . . }, "dir2": { "file3.java": { "method3": ["hello", "hi"], "method4": [] "file4.java": { } } } i have have list of strings like
list = ["dir1", "dir2", "file3.java", "method3"] is there easy way traverse dictionary access data in method3 using list able call
dict[list] and have like
dict["dir1"]["dir2"]["file3.java"]["method3"] and return
["hello", "hi"] but have no idea how long list of strings list
list = ["file1.java","method1"] also needs work
you can use reduce built-in function.
db = { "file1.java": { "method1": [], "method2": [] }, "dir1": { "dir2": { "file3.java": { "method3": ["hello", "hi"], "method4": [] }, "file4.java": { } } } } def lookup(db, path): return reduce(dict.get, path, db) print lookup( db, ["dir1", "dir2", "file3.java", "method3"] ) print lookup( db, ["file1.java","method1"] )
Comments
Post a Comment