I need a python function to extract an element from array of arbitrary depth -
i need process elements in array in python function - want assign default value if element doesn't exist. element processed may of arbitrary depth in array. ie, need this:
x=myfunc(myarray,"element","here")
but it's this:
x=myfunc(myarray,"deeper","element","here")
or even
x=myfunc(myarray,"even","deeper""element","here")
so achieve i've written terribly inefficient function myfunc
def myfunc(mydict,*args): if len(args) == 2 : try: returnvalue=mydict[args[0]][args[1]] except keyerror: returnvalue="some default value" elif len(args) == 3 : try: returnvalue=mydict[args[0]][args[1]][args[2]] except keyerror: returnvalue="some default value" elif len(args) == 4 : try: returnvalue=mydict[args[0]][args[1]][args[2]][args[3]] except keyerror: returnvalue="some default value" return returnvalue
yes, know could assign value directly x , put except keyerror: around assignments, of course i've stripped example down simplify it.
i know there has better way of extracting element array of arbitrary depth - if change args ("list","of","elements") ["list"]["of"]["elements"] think i'd have it.
any ideas?
here's sample test using above:
def main(): mydict = { "first": { "second1": "2", "second2": "22", "deeper": { "third1": "3", "third2": "33" } } } x=myfunc(mydict,"first","second1") print "x should 2. , x is...",x x=myfunc(mydict,"first","deeper","third2") print "x should 33. , x is...",x x=myfunc(mydict,"first","hopefullygetdefaultreturned") print "x should 'some default value'. , x is...",x main()
a loop:
def get_by_path(value, *path): key in path: value = value[key] return value
with default:
def get_or_default(value, default, *path): try: return get_by_path(value, *path) except keyerror: return default
Comments
Post a Comment