Skip to content

Instantly share code, notes, and snippets.

@matteoferla
Created December 19, 2018 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteoferla/c2f50396ac3b766777b5831807bc0f83 to your computer and use it in GitHub Desktop.
Save matteoferla/c2f50396ac3b766777b5831807bc0f83 to your computer and use it in GitHub Desktop.
three methods, two to float-up the path to a key or value and one that given a dictionary and a tuple of keys/indices returns the value.
#python 3
# three methods, two to float-up the path to a key or value and one that given a convoluted nested dictionary and a tuple of keys/indices returns the value.
# float_key(dictionary,key)
# float_value(dictionary,key)
# get_value(dictionary,(keys/indices list))
# great for entrez, Uniprot, PDB XML dictionaries
# NB. works for dict and list like objects
import collections
def float_key(dex, key):
try:
if dex is str:
return False
elif isinstance(dex,collections.Mapping): #quacks like a dictionary
if key in dex:
return [key]
else:
for clavis in dex:
verdict = float_key(dex[clavis],key)
if verdict:
return [clavis, *verdict]
elif isinstance(dex,collections.Iterable): #quacks like a list
for i in range(len(dex)):
verdict=float_key(dex[i], key)
if verdict is not False:
return [i,*verdict]
else:
print('Unknown type',type(dex))
return False
except RecursionError:
return False
def float_value(dex, value):
try:
if dex is str:
return False
elif isinstance(dex, collections.Mapping): # quacks like a dictionary
for clavis in dex:
if value == dex[clavis]:
return [clavis]
else:
verdict = float_value(dex[clavis], value)
if verdict:
return [clavis, *verdict]
elif isinstance(dex, collections.Iterable): # quacks like a list
for i in range(len(dex)):
if value == dex[i]:
return [i]
else:
verdict = float_value(dex[i], value)
if verdict is not False:
return [i, *verdict]
else:
print('Unknown type', type(dex))
return False
except RecursionError:
return False
def get_value(dex, fields):
try:
inner = dex
for entry in fields:
inner = inner[entry]
return inner
except:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment