Python - 动态传递索引值

时间:2018-04-20 21:49:41

标签: python dictionary

我正在阅读一个名为response的深层嵌套字典并获取格式化输出

 response = {u'ResultSet': {u'Rows': [
{u'Data': [{u'VarCharValue': u'Table_name'}, {u'VarCharValue': u'Validation_Scenario'}, {u'VarCharValue': u'No_of_Records'}, {u'VarCharValue': u'Result'}]}, 
{u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'01_scenario2'}, {u'VarCharValue': u'100'}, {u'VarCharValue': u'FAIL'}]}, 
{u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'02_scenario1'}, {u'VarCharValue': u'200'}, {u'VarCharValue': u'FAIL'}]}, 
{u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'03_scenario3'}, {u'VarCharValue': u'300'}, {u'VarCharValue': u'PASS'}]}, 
{u'Data': [{u'VarCharValue': u'ABC'}, {u'VarCharValue': u'04_scenario4'}, {u'VarCharValue': u'400'}, {u'VarCharValue': u'PASS'}]}]}}

print (("{0[ResultSet][Rows][0][Data][0][VarCharValue]}".format(response)),
       ("{0[ResultSet][Rows][0][Data][1][VarCharValue]}".format(response)),
       ("{0[ResultSet][Rows][0][Data][2][VarCharValue]}".format(response)),
       ("{0[ResultSet][Rows][0][Data][3][VarCharValue]}".format(response))) 

Output: ('Table_name', 'Validation_Scenario', 'No_of_Records', 'Result')

现在当我想循环索引[0] [数据]从0到4我得到Python - TypeError:list indices必须是整数,而不是str

for i in range(4):
     print (("{0[ResultSet][Rows][i][Data][0][VarCharValue]}".format(response)),
            ("{0[ResultSet][Rows][i][Data][1][VarCharValue]}".format(response)),
            ("{0[ResultSet][Rows][i][Data][2][VarCharValue]}".format(response)),
            ("{0[ResultSet][Rows][i][Data][3][VarCharValue]}".format(response))) 

Error :TypeError: list indices must be integers, not str

我明白,因为有" "我被视为一个字符串,但我想知道如何动态传递索引值?

1 个答案:

答案 0 :(得分:2)

变量不会在字符串内扩展。如果你真的想用格式字符串来做这件事,你必须动态构建它:

for i in range(4):
     print ((("{0[ResultSet][Rows][" + str(i) + "][Data][0][VarCharValue]}").format(response)),
            (("{0[ResultSet][Rows][" + str(i) + "][Data][1][VarCharValue]}").format(response)),
            (("{0[ResultSet][Rows][" + str(i) + "][Data][2][VarCharValue]}").format(response)),
            (("{0[ResultSet][Rows][" + str(i) + "][Data][3][VarCharValue]}").format(response)))

或:

for i in range(4):
     print ((("{0[ResultSet][Rows][%d][Data][0][VarCharValue]}" % i).format(response)),
            (("{0[ResultSet][Rows][%d][Data][1][VarCharValue]}" % i).format(response)),
            (("{0[ResultSet][Rows][%d][Data][2][VarCharValue]}" % i).format(response)),
            (("{0[ResultSet][Rows][%d][Data][3][VarCharValue]}" % i).format(response))) 

但是在代码中访问嵌套元素会更简单,而不是格式字符串:

for i in range(4):
    print (response['ResultSet']['Rows'][i]['Data'][0]['VarCharValue'],
           response['ResultSet']['Rows'][i]['Data'][1]['VarCharValue'],
           response['ResultSet']['Rows'][i]['Data'][2]['VarCharValue'],
           response['ResultSet']['Rows'][i]['Data'][3]['VarCharValue'])