我有以下字典,我只想从中获取'tcase_name'
a = {'179781': [{'exec_id': '0',
'exec_on_build': '',
'exec_on_tplan': '',
'exec_status': 'n',
'execution_duration': '',
'execution_order': '1',
'execution_type': '2',
'external_id': '59',
'feature_id': '14799',
'full_external_id': 'TC-59',
'platform_id': '0',
'platform_name': '',
'status': '1',
'tc_id': '179781',
'tcase_id': '179781',
'tcase_name': 'test_20experiment', # HERE
'tcversion_id': '179782',
'tcversion_number': '',
'version': '1'}],
'179821': [{'exec_id': '68588',
'exec_on_build': '160',
'exec_on_tplan': '178775',
'exec_status': 'b',
'execution_duration': '0.00',
'execution_order': '1',
'execution_type': '2',
'external_id': '60',
'feature_id': '14800',
'full_external_id': 'TC-60',
'platform_id': '0',
'platform_name': '',
'status': '1',
'tc_id': '179821',
'tcase_id': '179821',
'tcase_name': 'test_22experiment', # AND HERE
'tcversion_id': '179822',
'tcversion_number': '1',
'version': '1'}]}
以下是我的尝试:
>>> a.keys()
['179821', '179781']
>>> a.values()
[[{'tcase_id': '179821', 'status': '1', 'exec_id': '68588', 'tcversion_id': '179822', 'exec_on_tplan': '178775', 'version': '1', 'external_id': '60', 'tcversion_number': '1', 'tc_id': '179821', 'execution_type': '2', 'platform_id': '0', 'tcase_name': 'test_22experiment', 'execution_duration': '0.00', 'exec_on_build': '160', 'exec_status': 'b', 'full_external_id': 'TC-60', 'feature_id': '14800', 'execution_order': '1', 'platform_name': ''}], [{'tcase_id': '179781', 'status': '1', 'exec_id': '0', 'tcversion_id': '179782', 'exec_on_tplan': '', 'version': '1', 'external_id': '59', 'tcversion_number': '', 'tc_id': '179781', 'execution_type': '2', 'platform_id': '0', 'tcase_name': 'test_20experiment', 'execution_duration': '', 'exec_on_build': '', 'exec_status': 'n', 'full_external_id': 'TC-59', 'feature_id': '14799', 'execution_order': '1', 'platform_name': ''}]]
>>> a.values()['tcase_name']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
有人可以建议我从这个字典中获取所需的字段值吗?
答案 0 :(得分:0)
你做得对的。对于嵌套字典,如果您无法理解,请将其打印出来以查看其结构。
这是一种获取你应该能够操纵的价值的方法,以获得你想要的任何东西。
for k,v in a.items(): # get the keys and values in the dict a. k, v are not special names.
for e in v: # now lets get all of the elements in each value, which is a list of dicts
print(e.get('tcase_name')) # use the dict method get to retrieve the value for a particular key of interest.