Home > Blockchain >  Get value from an array that stores a tree of keys in python
Get value from an array that stores a tree of keys in python

Time:12-02

I have an array that stores a key tree from a dictionary. For example

person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}, ...]

Becomes

key_tree = [0, "person", "first_name"]

OR

key_tree = [0, "person", "age_of_children"]

This array count contain one item or many items.

I'd like to get the value from the person_dict, "John" in this case, by using the key_tree array dynamically. I would then like to set a different value for it.

CodePudding user response:

person_dict['person'].update({'first_name':'Ahmad'})

or

person_dict[key_tree[0]].update({key_tree[1]: 'Ahmad'})

CodePudding user response:

You can try the following:

def get_value(d, key_list):
    for key in key_list:
        d = d[key]
    return d


def set_value(d, key_list, value):
    res = d
    *keys, last_key = key_list

    for key in keys:
        d = d[key]

    d[last_key] = value
    return res


person_dict = [{"person": {"first_name": "John", "age_of_children": [1, 8, 13]}}]
key_tree = [0, "person", "first_name"]

print(get_value(person_dict, key_tree))
print(set_value(person_dict, key_tree, "John2"))

output:

John
[{'person': {'first_name': 'John2', 'age_of_children': [1, 8, 13]}}]

For getting values just use get_value, it's pretty simple. In set_value you need to iterate until before the last key, so that you can assign new value to the last object. After the for-loop, d is your last container(dict or list or whatever object who can is subscriptable) object, you can update the last_key value with the value of value. res = d line is needed because you need to have a reference to the most outer container otherwise after the for-loop you have only the last inner container.

  • Related