Skip to content

Instantly share code, notes, and snippets.

@VishalTaj
Last active December 10, 2015 13:14
Show Gist options
  • Save VishalTaj/1ac8e3d63d980c411dc0 to your computer and use it in GitHub Desktop.
Save VishalTaj/1ac8e3d63d980c411dc0 to your computer and use it in GitHub Desktop.
Fetching value from a nested dictionary
#!/usr/bin/python
__author__ = 'Vishal Taj PM'
def getDicKeyValue(data,search):
'''
This can also be used to get data from json object
Instruction
Function accepts 2 parameter
1 A nested dictionary
2 List of Keys in order to travers
'''
dataPos = data
for s in search:
if isinstance(dataPos,dict):
if dataPos.has_key(s):
dataPos = dataPos[s]
elif isinstance(dataPos,list):
if len(dataPos) > 1:
dataList = []
for datas in dataPos:
if datas.has_key(s):
dataList.append(datas[s])
dataPos = tuple(dataList)
elif dataPos[0].has_key(s):
dataPos = dataPos[0][s]
return dataPos
search = ['formProperties','enumValues','id']
print getDicKeyValue(data,search)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment