Skip to content

Instantly share code, notes, and snippets.

@utgwkk
Created November 4, 2016 08:22
Show Gist options
  • Save utgwkk/c6b21d6bbc8b01c13cef495cc743ff49 to your computer and use it in GitHub Desktop.
Save utgwkk/c6b21d6bbc8b01c13cef495cc743ff49 to your computer and use it in GitHub Desktop.
dig implementation in Python
def dig(dic, *keys):
keys = list(keys)
if isinstance(keys[0], list):
return dig(dic, *keys[0])
if isinstance(dic, dict) and keys[0] in dic or \
isinstance(dic, list) and keys[0] < len(dic):
if len(keys) == 1:
return dic[keys[0]]
return dig(dic[keys[0]], *keys[1:])
return None
if __name__ == '__main__':
h = { 'foo': { 'bar': { 'baz': 1 } } }
print(dig(h, 'foo', 'bar', 'baz'))
g = { 'foo': [10, 11, 12] }
print(dig(g, 'foo', 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment