遍历嵌套的dict项

时间:2018-11-05 17:14:25

标签: html python-3.x

<?php    
$serverName = "VM4FE8D04";   
$databaseName = "NNPC-ChevronScholarship";   

$connectionInfo = array("Database"=>$databaseName);                               


/* Connect using SQL Server Authentication. */    
$conn = sqlsrv_connect( $serverName, $connectionInfo);    

$tsql = "SELECT * FROM ExamSlip";    

/* Execute the query. */    

$stmt = sqlsrv_query( $conn, $tsql);    

if ( $stmt )    
{    
     echo "Statement executed.<br>\n";    
}     
else     
{    
     echo "Error in statement execution.\n";    
     die( print_r( sqlsrv_errors(), true));    
}    

/* Iterate through the result set printing a row of data upon each iteration.*/    

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))    
{    
     echo "Name: ".$row[Names]."\n";    
     echo "Application No: ".$row[ApplicationNo]."\n";    
     echo "Serial No: ".$row[SerialNo]."<br>\n";    
     echo "-----------------<br>\n";    
}    

/* Free statement and connection resources. */    
sqlsrv_free_stmt( $stmt);    
sqlsrv_close( $conn);    
?>    

我有一个返回此字典的函数,但我想遍历该字典并检索href链接,但到目前为止我没有尝试过。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您所拥有的没有字典-它是该字典各项的视图(可能是通过my_dict.items()获得的。)

对于您来说,看来您可以通过my_dict["props"]["children"][1]["props"]["children"]["props"]["href"]访问该链接,但是如果您告诉我们您的词典确切来自何处,我相信还有更好的方法。


如果没有其他方法,可以使用递归函数:

def find_value(d, key="href"):
    if isinstance(d, dict):
        for key in d:
            if key == "href":
                return d[key]
            result = find_value(d[key], key)
            if result:
                return result
    elif isinstance(d, list):
        for element in d:
            result = find_value(element, key)
            if result:
                return result

然后您可以用字典来调用它:

>>> find_value(my_dict)
'http:group.net/advsot_output/advsot_20181104.xlsx'

如果可能多次出现该密钥,并且您希望能够找到所有密钥,请使用此生成器替代方法:

def find_values(d, key="href"):
    if isinstance(d, dict):
        for key in d:
            if key == "href":
                yield d[key]
            yield from find_values(d[key], key)
    elif isinstance(d, list):
        for element in d:
            yield from find_values(element, key)

您可以通过迭代来使用它:

>>> for url in find_values(my_dict, "href"):
...     print(url)
group.net/advsot_output/advsot_20181104.xlsx

如果您只想要列表,请在其上调用list()

>>> list(find_values(my_dict, "href"))
['group.net/advsot_output/advsot_20181104.xlsx', ...]