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

HectorOfTroy407

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

for k,v in A_FIELDS.iteritems()

    print k + "= " resultsDict[v]

对于下面的A_FIELDS字典中的每个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)的值周围进行“”。

知道如何使用这些值来访问字典和打印键,以便英语可读吗?谢谢

虎鹰T3

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python-在字典中使用numpy数组作为键的替代方法

为什么我不能在Python中使用列表作为字典键?

为什么我不能在Python中使用列表作为字典键?

如何在python中使用重复键创建嵌套字典

使用列表作为值的Python字典,查找具有相同值的其他键

使用Python字典值返回键作为结果

在Python中使用相同的键在字典中查找不同的值

如何使用Python比较来自同一字典键的嵌套字典值

Python在嵌套字典中搜索键/值

如何在Python中使用键扩展字典中的值

使用python删除嵌套字典中的键及其值

Python:使用列表作为字典键

Python嵌套字典从嵌套值检索键

在python中使用相同的键但值不同的字典/列表更新

如何在Python的嵌套字典中使用相同的键获取所有值?

如何在python中使用相同的键组合(附加值)两个嵌套字典?

Python使用变量作为键从字典检索值

Python嵌套字典键,值交换

使用Volt :: Model作为键/值对的字典

在Python中使用列表作为值的操作搜索字典

Python:使用“值”作为字典获取前n个键

在python中检查键,嵌套字典的值?

使用嵌套键数组过滤出Python字典值

python:使用字典键的一部分作为字典值的变量

在 Python 中使用键和值附加到字典中

在元组中使用两个值作为 python 字典中的键

python - 如何在Python3中使用键和值数组作为二维列表从用户那里获取字典?

如何在 Python 中使用多个键修改嵌套字典中的一组特定值?

python:字典键作为行索引,值作为列标题。如何使用字典引用并选择 df 中的特定值?