Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List to access dict directly [duplicate]

Tags:

python

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 ?

like image 349
John Prawyn Avatar asked Sep 13 '26 20:09

John Prawyn


2 Answers

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'
like image 50
DSM Avatar answered Sep 16 '26 10:09

DSM


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...

like image 33
Jon Clements Avatar answered Sep 16 '26 11:09

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!