Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get to a dict key from a list?

lets say I have the following dict structure and a list of keys.

d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}
keyList = ['a', 'b', 'c']

What is a pythonic way to reference the value of the c key in a dynamic way? In a static way I would say something like d[a][b][c] however if my keyList is dynamic and I need to reference the value at runtime is there a way to do this? the len of keyList is variable.

The main problem is i really don’t know what to search. I tried things like dynamic dictionary path but couldn’t get anything remotely close

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}

key_list = ['a', 'b', 'c']

# Use the `get` method to traverse the dictionary and get the value at the specified path
value = d
for key in key_list:
    value = value.get(key, {}) # suggested by @sahasrara62

# Print the value
print(value)  # Output: 'value'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading