一个衬垫从字典python中查找嵌套值

问题描述 投票:4回答:3

假设我有一个任意嵌套的字典:

d = {
    11: {
        21: {31: 'a', 32: 'b'},
        22: {31: 'a', 34: 'c'},
    },
    12: {
        1: {2: 3}
    }
}

还有一个键列表,其位置告诉我哪个嵌套字典可以查找每个键:

keys = [11, 21, 31]
# keys = [11, 23, 44]

有一个简单的衬垫来做这个吗?我看了下面列出的问题,它们是相似的,但不是我真正想要的。我自己也试过了,想出了这个:

from functools import reduce

def lookup(d, key):
    return d.get(key, {}) if d and isinstance(d, dict) else None

def fn(keys, d):
    return reduce(lookup, keys, d)

print(fn(keys, d)) # prints 'a'

这样做的问题是,如果是第二个键列表(参见注释掉的键),它会继续查找嵌套键,即使没有找到更高级别的键,继续也没有意义。如果我找到最终匹配或失败,我怎么能停止reduce(下面列出的一个问题解决了它,但我不能在我的用例中真正应用它......或者我可以吗?)?还有其他想法吗?哦,我想用官方的python库来完成这个。所以没有numpypandas等,但functoolsitertools很好

Python: Convert list to dict keys for multidimensional dict with exception handling

Is there a simple one-liner for accessing each element of a nested dictioanry in Python?

Accessing nested values in nested dictionaries in Python 3.3

Using itertools for recursive function application

Stopping a Reduce() operation mid way. Functional way of doing partial running sum

Finding a key recursively in a dictionary

谢谢!

python dictionary reduce functools
3个回答
7
投票

你可以使用functools.reduce()

from functools import reduce # In Python 2, don't import it. (It's a built-in)

print(reduce(dict.get, keys, d))

# 'a'

对于你提到的键,它是这样的:

  • dict.get(初始)和dkeys)的第一项调用11来获得d[11]
  • 用结果(字典)和dict.getkeys)中的下一个项目调用21来获取{...}[21]
  • 打电话给dict.get ...... ...

直到keys“减少”到最终值('a'

编辑:如果没有这样的密钥,dict.get导致None,可能会有不良结果。如果你想要一个KeyError,你可以使用operator.getitem代替。


0
投票

这是我提出的解决方案,当给出无效的查找路径时,它还会返回有用的信息,并允许您挖掘任意json,包括嵌套列表和dict结构。 (对不起,这不是一个单行)。

def get_furthest(s, path):
    '''
    Gets the furthest value along a given key path in a subscriptable structure.

    subscriptable, list -> any
    :param s: the subscriptable structure to examine
    :param path: the lookup path to follow
    :return: a tuple of the value at the furthest valid key, and whether the full path is valid
    '''

    def step_key(acc, key):
        s = acc[0]
        if isinstance(s, str):
            return (s, False)
        try:
            return (s[key], acc[1])
        except LookupError:
            return (s, False)

    return reduce(step_key, path, (s, True))

-2
投票
d = {
    11: {
        21: {
            31: 'a from dict'
        },
    },
}

l = [None] * 50
l[11] = [None] * 50
l[11][21] = [None] * 50
l[11][21][31] = 'a from list'

from functools import reduce

goodkeys = [11, 21, 31]
badkeys = [11, 12, 13]

print("Reducing dictionary (good):", reduce(lambda c,k: c.__getitem__(k), goodkeys, d))
try:
    print("Reducing dictionary (bad):", reduce(lambda c,k: c.__getitem__(k), badkeys, d))
except Exception as ex:
    print(type(ex), ex)

print("Reducing list (good):", reduce(lambda c,k: c.__getitem__(k), goodkeys, l))

try:
    print("Reducing list (bad):", reduce(lambda c,k: c.__getitem__(k), badkeys, l))
except Exception as ex:
    print(type(ex), ex)
© www.soinside.com 2019 - 2024. All rights reserved.