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

2024-10-02 12:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

for k,v in A_FIELDS.iteritems()

    print k + "= " resultsDict[v]

在下面的A\u字段中,每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)的值周围使用“”。你知道吗

你知道我如何使用这些值来访问字典并打印关键字,这样它就可以用英语阅读了吗?谢谢


Tags: 元素fields字典格式allrequests引号total
1条回答
网友
1楼 · 发布于 2024-10-02 12:37:18

将每个密钥存储在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

相关问题 更多 >

    热门问题