字典作为字典中的值

时间:2015-09-23 16:12:25

标签: python dictionary

有一个字典作为里面的字典,如下所示:

{'a': {'b': 'c', 'd': 'e', 'f': 'g'}, 'h': {'i': 'j', 'k': 'l', 'm': 'n'}}

怎么可能访问,让我们说; ' f'为#' a'生成'?

1 个答案:

答案 0 :(得分:4)

只是链式关键查找:

outer_dictionary['a']['f']

此处dictionary['a']返回键'a'的值,该键本身就是一个字典。

您还可以存储中间结果:

nested_dictionary = outer_dictionary['a']
nested_dictionary['f']

这完全相同,但也留下了另一个对nested_dictionary可用的嵌套字典的引用。

快速演示:

>>> nested_dictionary = {'a': {'b': 'c', 'd': 'e', 'f': 'g'}, 'h': {'i': 'j', 'k': 'l', 'm': 'n'}}
>>> nested_dictionary['a']
{'b': 'c', 'd': 'e', 'f': 'g'}
>>> nested_dictionary['a']['f']
'g'