Getting dictionary value when part of a key is in a string

Take the dictionary

dict = {"word":{"a":{"b":2}}}

I want to get a value of 2. To access this, I can do this dict["word"]["a"]["b"]

However, I want to know if I can have part of the key (section ["a"]["b]) in the line

And refer to it something like this:

string = "[\"a\"][\"b\"]"

dict["word"]string

Or something like this

I know this syntax is incorrect, but is it possible to do something like this?

in Python 3.x

EDIT: A better example might be this

    dict = {
"word":{"a":{"b":2}}
"hello":{"a":{"b":1}}
"mouse":{"a":{"b":5}}
}

How to get the value of b in each case? where you want to avoid hard coding into a bit of the ["a"]["b"]key in case of change.

+4
source share
2 answers

dict , .


- re module. , . , - .

>>> d = {"word":{"a":{"b":2}}}
>>> s = '["a"]["b"]'
>>> import re
>>> keys = re.findall(r'\["(.+?)"\]',s)
>>> d["word"][keys[0]][keys[1]]
2

, reduce functools. ( JonClements comment)

>>> import functools
>>> functools.reduce(dict.__getitem__, keys, d['word'])
2

dicts

>>> d = {
... "word":{"a":{"b":2}},
... "hello":{"a":{"b":1}},
... "mouse":{"a":{"b":5}}
... }
>>> [functools.reduce(dict.__getitem__, keys, d[i]) for i in d]
[2, 5, 1]

, - , . ( dict),

>>> {i:functools.reduce(dict.__getitem__, keys, d[i]) for i in d}
{'word': 2, 'mouse': 5, 'hello': 1}
+3

- , . charachter, , ., , $, | .

def get(d, key):
    kp = key.split('.')
    for k in kp:
        d = d[k]
    return d

d = {'a': {'b': 2}}
get(d, 'a.b')
>>> 2

EDIT :

, a.b ? ,

d = {
 "word":{"a":{"b":2}},
 "hello":{"a":{"b":1}},
 "mouse":{"a":{"b":5}},
}

# nesting calls to get just to show it is flexible like that
[get(get(d, k), 'a.b') for k in d.keys()]
# if you wanted to generate a dict of {"word": val} it would look like this
{k:get(get(d, k), 'a.b') for k in d.keys()}

,

d = {
 "x": {"word":{"a":{"b":2}}},
 "x": {"hello":{"a":{"b":1}}},
 "x": {"mouse":{"a":{"b":5}}},
}

# using more calls to get just to show it is flexible like that
[get(get(d, 'x.'+k), 'a.b') for k in get(d, 'x').keys()]
+2

All Articles