Answer the question
In order to leave comments, you need to log in
How to get data from such a dictionary?
There is a dictionary: data ={'a': {'b': {'c': 1}}}
You need to get the value of the key 'c' using this construction data[key], while this option does not fit data['a']['b']['c']. How to do it?
Answer the question
In order to leave comments, you need to log in
Python 3. but this is a crutch of course.
from functools import reduce
class CustomDict(dict):
def __getitem__(self, key):
return reduce(lambda acc, x: acc.__getitem__(x), key.split('.'), super())
data = CustomDict({'a': {'b': {'c': 1}}})
print(data['a.b.c'])
The meaning is the same as
data['a']['b']['c']
((data.get('a')).get('b')).get('c')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question