Python - "map"字典的键列表

标签 python list dictionary syntax

我有一个 Python 多维字典,我有一个列表,其中包含我想要访问的键。从字典中获取值的最简单方法是什么?

例子:

main = {
    'one': {
        'two': {
            'three': "Final word"
        }
    }
}

mylist = ['one', 'two', 'three']

# and I want to print out the value of `three` ("Final word")

最佳答案

遍历 mylist,存储一个中间字典(我称之为 submain),直到用完 mylist 元素:

submain = main
for key in mylist:
    submain = submain[key]
print submain

关于Python - "map"字典的键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210071/

相关文章:

python - 将列表变量写入文件

python - 具有多列的 Pandas Correlation GroupBy

c++ - 在 C++ 中实现 map<mpz_t, double>

swift - 如何在swift中创建一个具有字符串和函数作为键值对的字典

python - 为什么我的地理定位不起作用?

python - 什么最适合字符串提取或模式匹配 regex/awk/emacs lisp?

java - 在java中覆盖列表结果类型

python - 使用 Python2.6 抓取时抓取子字符串

python - 尝试从列表中访问索引并将其转换为 python 中的字符串

python - 如何使用字典而不是大量 if/else 语句在 Python 中创建测验?