【问题标题】:How to reduce a nested dict?如何减少嵌套的字典?
【发布时间】:2021-01-26 13:10:51
【问题描述】:

我有一个嵌套的dictdict),并希望能够通过一个函数,通过给出“路径”来访问任何深度的元素。换句话说,通过调用myfunc(hello, 'world', 'bonjour')(我将其定义为def myfunc(mydict, *what))来访问hello['world]['bonjour']

我没有找到任何内置的,所以我尝试了

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'))

这会崩溃

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

我不确定问题出在哪里(或者 - 是否有这样的功能,所以我不需要重新发明轮子)

【问题讨论】:

标签: python dictionary lambda


【解决方案1】:

改成:

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 需要一个函数,该函数接受两个参数并返回可用作自身第一个参数的内容。

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

为您的数据执行此操作。您还必须传递正确的起始值,即 self.data 字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2020-05-30
    • 2015-07-03
    • 2016-12-11
    • 2017-10-13
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多