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: "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.
精彩评论