当前位置: 代码迷 >> 综合 >> python Dict/List检索选择器嵌套值
  详细解决方案

python Dict/List检索选择器嵌套值

热度:73   发布时间:2023-12-02 06:27:44.0

从字典或列表中检索给定选择器列表指示的嵌套键的值。

使用functools.reduce()遍历selectors列表。
申请operator.getitem()中的每个键selectors,检索用作下一次迭代的迭代器的值。

python

from functools import reduce 
from operator import getitemdef get(d, selectors):return reduce(getitem, selectors, d)
#例子
users = {
    'freddy': {
    'name': {
    'first': 'fred','last': 'smith' },'postIds': [1, 2, 3]}
}
get(users, ['freddy', 'name', 'last']) # 'smith'
get(users, ['freddy', 'postIds', 1]) # 2

functions

# functions
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__"""reduce(function, sequence[, initial]) -> valueApply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the itemsof the sequence in the calculation, and serves as a default when thesequence is empty."""pass

operator

def getitem(a, b):"Same as a[b]."return a[b]
  相关解决方案