Last active
July 21, 2020 22:00
-
-
Save nitrocode/d1fdc012994a75b865e043523f8f2eb7 to your computer and use it in GitHub Desktop.
Gets a value from a dictionary using a list key path
This file contains hidden or 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
#!/usr/bin/env python | |
def getDictValueFromPath(listKeys, jsonData): | |
"""Retrieve value from a dictionary using a list of keys. | |
>>> mydict = { | |
'a': { | |
'b': { | |
'c': '1' | |
} | |
} | |
} | |
>>> mykeys = ['a', 'b'] | |
>>> getDictValueFromPath(mykeys, mydict) | |
{'c': '1'} | |
:param listKeys: list of dictionary keys | |
:param jsonData: dictionary to search through | |
""" | |
localData = jsonData.copy() | |
for k in listKeys: | |
try: | |
localData = localData[int(k)] if k.isdigit() else localData[k] | |
except: | |
localData = localData[k] | |
return localData | |
mydict = {'a': {'b': {'c': '1'}}} | |
mykeys = ['a', 'b'] | |
print(getDictValueFromPath(mykeys, mydict)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment