【问题标题】:Nested indexing in pythonpython中的嵌套索引
【发布时间】:2016-12-06 21:26:21
【问题描述】:

我有一个 python 字典,它的一些(但不是全部)值也是字典。

例如:

    d = {'a' : 1,
         'b' : {'c' : 3, 'd' : 'target_value'}
        }

传递键以达到任何目标值的最佳方式是什么?像retrieve(d, (key, nested_key, ...)) 这样的东西retrieve(d, ('b','d')) 会返回target value

【问题讨论】:

  • 你从哪里得到疯狂的数据结构?
  • 我正在解析一个文件并将其组织到有时嵌套的字典中。但这适用于任何嵌套的可索引数据结构。
  • 我的错误,retrieve(d, ('b', 'd')) 应该返回 target_value

标签: python dictionary nested key


【解决方案1】:

这里更好的选择是找到一种方法来规范您的数据结构,但如果由于某种原因不能,您可以按顺序访问每个键。

例如:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    for key in keys[1:]:
        val = val[key]
    return val
d = {'a' : 1,
     'b' : {'c' : 3, 'd' : 'target_value'}
    }
print(nested_getter(d, 'b', 'd'))

你也可以递归地做:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    if isinstance(val, dict):
        return nested_getter(val, *keys[1:])
    else:
        return val

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2013-12-18
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    相关资源
    最近更新 更多