Created
November 4, 2016 08:22
-
-
Save utgwkk/c6b21d6bbc8b01c13cef495cc743ff49 to your computer and use it in GitHub Desktop.
dig implementation in Python
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
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