Marçal Torà Marçal Torà - 1 year ago 105
Python Question

Python Get dictionary value with a key list

Considering I have

users = \
'Sam': {
'age': 19,
'location': 'Flodira',
'country': 'United States'
'Max': {
'age': 16,
'location': 'Sydney',
'country': 'Australia'

def getUserValue(query):
return users[query]

getUserValue(['Sam', 'location'])

How could I do this? I know I could straightly do
, what I would like to do is get Sam's location via a list object.

Answer Source

For a more general solution than Jared's, you could use list unpacking with a recursive function..

def getUserValue(dic, lis):
    if len(lis) > 1:
        return getUserValue(dic[lis[0]], lis[1:])
        return dic[lis[0]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download