0

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;
}
2
  • Please provide a better clue as to what the table structure is. The PHP code isn't the ideal way to show a SQL table structure. Commented Jan 11, 2011 at 18:33
  • the table structure is complex as it uses 3 INNER JOIN's and I didn't really want to explain all the relationships, hence the simplified question. Its not even geographic but i used areas as they are easy to relate to. Commented Jan 11, 2011 at 18:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i would tick this but i have no idea what lambda does - and I have tried to understand it. +1 anyways.
@khany: Don't understand lambda? Step 1. search. It's been asked here. Step 2. search. There are long essays available on Google. Step 3. try it. It's pretty clear how it works and you can play with code in Python to see how things work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.