I have a document like this:
>>> k = {'finance_pl':{'S':{'2008':45,'2009':34}}}
Normal way to access is:
>>> k['finance_pl']['S']
{'2008': 45, '2009': 34}
But, in my case the end user will give me input as finance_pl.S
I can split this and access the dictionary like this:
>>> doc_list = doc.split('.')
>>> k[doc_list[0]][doc_list[1]]
{'2008': 45, '2009': 34}
But, I don't want to do this, since the dictionary structure may change the and
user can give something like this finance_pl.new.S instead of k['finance_pl']['S'] or k[doc_list[0]][doc_list[1]].
I need something to apply the users input directly (Ex: if input is finance_pl.new.S, I should be able to apply this .split('.') method to the users input and apply directly).
What is the elegant way to do that ?
I'd simply loop over all the parts:
def getter(somedict, key):
parts = key.split(".")
for part in parts:
somedict = somedict[part]
return somedict
after which we have
>>> getter(k, "finance_pl.S")
{'2008': 45, '2009': 34}
or
>>> getter({"a": {"b": {"c": "d"}}}, "a")
{'b': {'c': 'd'}}
>>> getter({"a": {"b": {"c": "d"}}}, "a.b.c")
'd'
You could go for something like:
k = {'finance_pl':{'S':{'2008':45,'2009':34}}}
print reduce(dict.__getitem__, 'finance_pl.S.2009'.split('.'), k)
# 34
If you're using Python 3.x, you'll need a from functools import reduce in there...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With