【问题标题】:Python - Access hierarchical dict element from list of keysPython - 从键列表访问分层字典元素
【发布时间】:2016-03-16 13:01:42
【问题描述】:

假设我有一个常规的“dict-of-dicts”,如下所示:

d = {}
d['a'] = {}
d['a']['b'] = 3

我当然可以使用d['a']['b'] 访问该元素。

就我而言,我有一个递归应用程序,在其中我将当前状态保留为键列表。所以我会有

my_key = ['a', 'b']

如何使用 my_key 访问值 3?当然,问题在于my_key 可以任意长(深)。

我意识到我可以编写另一个遍历函数,但似乎应该有一种直接的方法。有什么想法吗?

【问题讨论】:

  • 我不认为这是一个足够普遍(或足够明智)的案例来保证一个函数。自己写 - 大概 4 行。
  • 您能否修复您的示例,因为它没有任何意义,以及键可以嵌套多深?
  • @PadraicCunningham 抱歉,现在修好了..

标签: python dictionary recursion


【解决方案1】:

您可以使用reduce 使用不同的键迭代地索引字典的每一层:

>>> from functools import reduce #only necessary in 3.X
>>> d = {}
>>> d['a'] = {} #I'm assuming this is what you meant to type
>>> d['a']['b'] = 3
>>> keys = ("a", "b")
>>> reduce(dict.get, keys, d)
3

【讨论】:

  • 正是我想要的!谢谢!
【解决方案2】:

目前字典键只能是hashable类型,listListType)不是其中之一,所以如果你尝试指定一个列表作为字典键:

{}[[]]

你会得到:

TypeError: unhashable type: 'list'`.

您可以增强当前字典,允许将列表指定为键,并在内部对象上迭代列表。这是代码(注意它只处理 get/read 部分):

from types import DictType, ListType

class EnhancedDictType(DictType):
    def __getitem__(self, key):
        if key and isinstance(key, ListType):
            new_obj = self
            for item in key:
                new_obj = new_obj[item]
            return new_obj
        else:
            return super(EnhancedDictType, self).__getitem__(key)

dict = EnhancedDictType

这里还有一些测试代码:

d = dict()
d[1] = dict()
d[1][2] = dict({3: 4})
d[(1, 2, 3)] = 5
print d
print d[1]
print d[1][2]
print d[[1, 2]]
print d[[1 ,2, 3]]
print d[(1, 2, 3)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2023-04-06
    • 2015-07-05
    • 2011-07-21
    • 2021-07-27
    相关资源
    最近更新 更多