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

时间:2016-04-12 21:22:11

标签: python dictionary reduce functools

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

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很好

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

{{3}}

谢谢!

3 个答案:

答案 0 :(得分: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(首字母)和d keys的第一项11致电d[11]以获取dict.get
  • 使用结果(字典)和keys21)中的下一个项目调用{...}[21]以获取dict.get
  • 致电keys ...
    ...

直到'a'"减少"到最终值(dict.get

修改:如果没有此类密钥,None会产生KeyError,可能会产生意外结果。如果您想拥有class Link { public Object s; public Link next; public Link(Object Student) { s=Student; next=null; } } ,则可以改为使用operator.getitem

答案 1 :(得分:0)

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

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 :(得分:-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)