在Python字典中使用嵌套键作为值

时间:2016-07-12 02:40:33

标签: python dictionary nested

我正在尝试将英语描述映射到我需要从字典中访问的嵌套元素,这样我就可以用英语可读格式呈现数据。例如,我将打印如下内容:

for k,v in A_FIELDS.iteritems()

    print k + "= " resultsDict[v]

对于下面的A_FIELDS Dict中的每个k,v。

A_FIELDS = {
        'Total Requests'    :   "['requests']['all']",
        'Cached Requests'   :   "['requests']['cached']",
        'Uncached Requests' :   "['requests']['uncached']",
        'Total Bandwidth'   :   "['bandwidth']['all']",
        'Cached Bandwidth'  :   "['bandwidth']['cached']",
        'Uncached Bandwidth':   "['bandwidth']['uncached']",
        'Total Page View'   :   "['pageviews']['all']",
        'Total Uniques'     :   "['uniques']['all']"
    }

但是,无论我如何格式化字典,我都会遇到两个错误之一。我试过“”没有内部引号(keyError)的值,只有内部引号(列表索引必须是整数而不是str)。

知道如何使用这些值来访问字典并打印密钥以使其具有英文可读性吗?感谢

1 个答案:

答案 0 :(得分:1)

将每个密钥存储在list

resultsDict = {'requests':{'all':0, 'cached':1, 'uncached':2},
'bandwidth':{'all':0, 'cached':1, 'uncached':2},
'pageviews':{'all':0, 'cached':1, 'uncached':2},
'uniques':{'all':0, 'cached':1, 'uncached':2}}

A_FIELDS = {
        'Total Requests'    :   ['requests', 'all'],
        'Cached Requests'   :   ['requests', 'cached'],
        'Uncached Requests' :   ['requests', 'uncached'],
        'Total Bandwidth'   :   ['bandwidth', 'all'],
        'Cached Bandwidth'  :   ['bandwidth', 'cached'],
        'Uncached Bandwidth':   ['bandwidth', 'uncached'],
        'Total Page View'   :   ['pageviews', 'all'],
        'Total Uniques'     :   ['uniques', 'all']
    }

如果您总是访问两个级别(例如'requests'然后'all'),只需解压缩密钥:

>>> for k,(v1,v2) in A_FIELDS.iteritems():
...     print '{} = {}'.format(k, resultsDict[v1][v2])
...
Total Page View = 0
Cached Bandwidth = 1
Uncached Requests = 2
Total Uniques = 0
Total Bandwidth = 0
Uncached Bandwidth = 2
Total Requests = 0
Cached Requests = 1

如果要访问任意深度,请使用循环:

>>> for k,v in A_FIELDS.iteritems():
...     result = resultsDict
...     for key in v:
...         result = result[key]
...     print '{} = {}'.format(k, result)
...
Total Page View = 0
Cached Bandwidth = 1
Uncached Requests = 2
Total Uniques = 0
Total Bandwidth = 0
Uncached Bandwidth = 2
Total Requests = 0
Cached Requests = 1