Home > Mobile >  Python change diction value from key in a string
Python change diction value from key in a string

Time:11-26

I have successfully used recursion to find a key to a variable I want to change in an API reponse json.

The recursion returns the key the equivilant is like this:

obj_key = "obj['key1']['key2'][1]['key3'][4]['key4'][0]"

if I eval this:

eval(obj_key)

I get the value no problem.

Now I want to change the value if it isn't what I want it to be. I can't figure this out and only get syntax error with every attempt .... all attempts are some form of:

eval(obj_key   ' = "my_new_value"'

I have slept on this one thinking it would come to me in a day or two (sometimes this works) but alas no epiphany for me. Thanks for any help!

CodePudding user response:

Using exec instead of eval seems solving this problem:

eval("y=12") #SyntaxError: invalid syntax

But replacing it with exec:

exec("y=12")
print(y) #12

CodePudding user response:

Instead of using eval, you could keep a list of keys and a reference to the object. So instead of building a string

"obj['key1']['key2'][1]['key3'][4]['key4'][0]"

You'd just need

obj

and

['key1', 'key2', 1, 'key3', 4, 'key4', 0]

Which are probably easier to create and manipulate.

To use this to get the value, you could write a function:

def my_get(obj, keys):  # TODO better name
    for key in keys:
        obj = obj[key]
    return obj

And to set a value:

def my_set(obj, keys, value):  # TODO better name
    last_obj = my_get(obj, keys[:-1])  # get the last dict or list, by skipping the last key
    last_obj[keys[-1]] = value  # now set the value using the last key
  • Related