I sometimes wanted to extract the values of dict and list using period-separated strings such as a.b
and c.d.2.e
, so I wrote them.
def get_item(src, path):
now = src
for i in path.split('.'):
if type(now) is list:
now = now[int(i)]
else:
now = now[i]
return now
now is a variable to put the current value. The initial value is the argument dict or list. Divide the path by a period and turn it by for. Swap the value of now until the end of for and finally return.
By the way, I don't expect the Key name to have a period.
my_dict = {
'a': {
'b': 'hello'
},
'c': {
'd':[
{'e': 3},
{'e': 4},
{'e': 5},
{'e': 6},
]
}
}
print(get_item(my_dict, 'a.b'))
print(get_item(my_dict, 'c.d.3.e'))
print(get_item(my_dict, 'c.d'))
# hello
# 6
# [{'e': 3}, {'e': 4}, {'e': 5}, {'e': 6}]
Recommended Posts