我试图将英语描述映射到我需要从字典访问的嵌套元素,以便我可以英语可读格式显示数据。例如,我将打印如下内容:
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)的值周围进行“”。
知道如何使用这些值来访问字典和打印键,以便英语可读吗?谢谢
将每个密钥存储在中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] 删除。
我来说两句