Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - How to reduce a nested dict?

I have a nested dict (of dict) and would like to be able, through a function, to access an element at any depth by giving the "path". In other words, access hello['world]['bonjour'] by calling myfunc(hello, 'world', 'bonjour') (which I would define as def myfunc(mydict, *what)).

I did not find anything built-in so I tried

import functools

class State:

    def __init__(self):
        self.data = {
            "a": 1,
            "b": {
                "c": 10
            }
        }

    def get(self, *what):
        return functools.reduce(lambda x: self.data[x], what)

state = State()
print(state.get('a', 'b'))

This crashes with

Traceback (most recent call last):
  File "C:/Users/yop/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/scratch_4.py", line 19, in <module>
    print(state.get('a', 'b'))
  File "C:/Users/yop/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/scratch_4.py", line 15, in get
    a = functools.reduce(lambda x: self.data[x], what)
TypeError: <lambda>() takes 1 positional argument but 2 were given

I am not sure where the problem is (or - is there such a function so that I do not need to reinvent the wheel)

question from:https://stackoverflow.com/questions/65902001/how-to-reduce-a-nested-dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change it to:

class State:
    # ...
    def get(self, *what):
        return functools.reduce(lambda d, x: d[x], what, self.data)

>>> s = State()
>>> s.get("a")
1
>>> s.get("b", "c")
10

reduce requires a function that takes two arguments and returns something that can be used as the first argument to itself.

lambda d, x: d[x]
# you could just take
# dict.get    OR
# dict.__getitem__

does that for your data. You also have to pass the proper start value which is the self.data dictionary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...