Skip to content
Advertisement

How do I create a dict of values from the results of an SQL query?

I’m trying to create a journey booking system in python/flask and am trying to create a dict of starting destinations and their ending destinations to allow me to run some ajax code which restricts the options of selecting destination based on the starting location like this (this is just an example of what I’m trying to create, not exactly the values I want):

I’ve got an SQL statement:

Which returns the following

I’ve created a dict that contains unique departing city names as follows:

Which prints:

Is there a way for me to populate the above dict with the corresponding arrival locations contained within the SQL statement?

Thanks.

Advertisement

Answer

You can use collections.defaultdict:

Output:

Edit: inclusion of departure and arrival times in final result:

Output:

You can also form the arrival locations themselves as dictionaries, instead of a list:

Output:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement