Home > Software engineering >  Get data from the dictionary by parameters from a variable in Python
Get data from the dictionary by parameters from a variable in Python

Time:08-03

I have dicts with

I get a dictionary from the database with about this structure. And also the path to the desired field of the form - ['extra_fields']['period'] - as a string. Can you please tell me how to turn this string into the path to the data in the dictionary, i.e. into this piece of code in python clt['extra_fields']['period'] or clt.get('extra_fields').get('period'). I'm sitting here thinking and can't figure out the best way to do it? The line with the path to the data can be anything, not just as in the example (so hardcoded is not an option)

clt = {
        "first_name": "test",
        "last_name": "test",
        "phone": "123",
        "client_id": 123,
        "email": "[email protected]",
        "father_name": "",
        "source": "test",
        "extra_fields": {
            "amount": 50000,
            "period": 90,
            "utm_source": "TEST_SOURCE",
            "utm_campaign": "TEST_CAMPAIGN",
            "keyword": "TEST_CREATIVE_ID"
        }
    }

CodePudding user response:

lets say path is correct so you can use it with eval or you can parse the keys and then using those parsed keys you can access the data.

example with eval is as, (considering dictionary access path is correct

>>> clt = {
...         "first_name": "test",
...         "last_name": "test",
...         "phone": "123",
...         "client_id": 123,
...         "email": "[email protected]",
...         "father_name": "",
...         "source": "test",
...         "extra_fields": {
...             "amount": 50000,
...             "period": 90,
...             "utm_source": "TEST_SOURCE",
...             "utm_campaign": "TEST_CAMPAIGN",
...             "keyword": "TEST_CREATIVE_ID"
...         }
...     }
>>> 
>>> path = "['extra_fields']['period']"
>>> 
>>> data = eval(f"clt{path}")
>>> data
90
>>> 

CodePudding user response:

You can convert the path to a list of paths using regex, and get the value using recursion

def get_value(_clt, path):
    value = _clt.get(path[0])
    if type(value) is dict:
        return get_value(value, path[1:])
    return value

path = "['extra_fields']['period']"
path = re.findall(r'\[(.*?)]', path.replace("'", ''))
print(get_value(clt, path)) # 90

path = "['last_name']"
path = re.findall(...)
print(get_value(clt, path)) # test
  • Related