【问题标题】:Using Nested Keys as Values in Python Dictionary在 Python 字典中使用嵌套键作为值
【发布时间】:2016-11-14 02:57:16
【问题描述】:

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

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)。

知道如何使用这些值来访问字典并打印键以便它是英文可读的吗?谢谢

【问题讨论】:

  • 我不知道你想要完成什么。与其重复使用术语“键”和“值”,不如通过示例输入/输出来解释您实际希望完成的任务,从而阐明您尝试完成的任务。
  • 很公平。我试图让它更清楚。我正在将英语单词映射到字典中的值。
  • 你想打印什么?你有一个奇怪的 string-inside-list-inside-string 事情正在发生。比如,如果我尝试A_FIELDS['Total Uniques'] 它应该打印什么?
  • 我正在尝试通过访问具有 ['uniques']['all'] 键的字典来打印标签(总唯一数)。我正在尝试将人类可读标签(Total Uniques)与实际值映射,这些值在字典中找到并位于 ['uniques']['all']。对不起,如果这不是更清楚。

标签: python dictionary nested


【解决方案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

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 2020-08-08
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多