当前位置: 动力学知识库 > 问答 > 编程问答 >

iteration - python convert sql result to tree hierarchy

问题描述:

i have a sql query that returns 3 levels of a data chain on each row (ie. Country, County, City). There may be more than 1 county per country and more than 1 city per county.

resultset:

"UK" "Lancashire" "Burnley"

"UK" "Lancashire" "Blackburn"

"UK" "Merseyside" "Liverpool"

"UK" "West Yorkshire" "Leeds"

"UK" "West Yorkshire" "York"

how do i iterate the resultset in python to create something like:

UK

->Lancashire

->->Burnley

->->Blackburn

->Merseyside

->->Liverpool

->West Yorkshre

->->Leeds

->->York

in php i would do something like:

while($row = $rec->fetch_object()) {

$var[$row->country]['county'][$row->county]['city'][$row->city] = $row->city;

}

网友答案:

This isn't ideal because it's kind of obscure.

ccc = defaultdict( lambda: defaultdict( list ) )
for row in cursor.fetchall():
    country, county, city = row
    ccc[country][county].append(city)

There are probably cleaner ways to do this.

分享给朋友:
您可能感兴趣的文章:
随机阅读: