Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Last active July 21, 2020 22:00
Show Gist options
  • Save nitrocode/d1fdc012994a75b865e043523f8f2eb7 to your computer and use it in GitHub Desktop.
Save nitrocode/d1fdc012994a75b865e043523f8f2eb7 to your computer and use it in GitHub Desktop.
Gets a value from a dictionary using a list key path
#!/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