开发者

python convert sql result to tree hierarchy

开发者 https://www.devze.com 2023-02-04 17:03 出处:网络
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.

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: "U开发者_开发问答K" "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.

0

精彩评论

暂无评论...
验证码 换一张
取 消