简体   繁体   English

如何从 SQL 查询的结果创建值的字典?

[英]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):我正在尝试在 python/flask 中创建一个旅程预订系统,并尝试创建一个起始目的地及其结束目的地的字典,以允许我运行一些 ajax 代码,该代码限制了基于像这样的起始位置选择目的地的选项(这只是我试图创建的一个例子,而不是我想要的值):

routes = {
            'Newcastle' : ['Bristol'],
            'Bristol' : ['Newcastle', 'New York', 'Manchester', 'Glasgow', 'Mainhead'],
            'Cardiff' : ['Edinburgh'],
            'Manchester' : ['Bristol', 'Birmingham', 'Glasgow', 'Southampton'],
            'London' : ['Manchester'],
            'Birmingham' : ['Newcastle'],
            'Edinburgh' : ['Cardiff']
        }

I've got an SQL statement:我有一个 SQL 声明:

SELECT_routes_statement = "SELECT c.city_name, r.departure_time, city.city_name, r.arrival_time, r.price, r.available_seats \
                               FROM routes r \
                               JOIN cities c ON r.departing_city_id=c.city_id \
                               JOIN cities city on r.arrival_city_id=city.city_id"

Which returns the following返回以下内容

[('Newcastle', datetime.timedelta(seconds=60300), 'Bristol', datetime.timedelta(seconds=82800), 140.0, 200), ('Bristol', datetime.timedelta(seconds=28800), 'Newcastle', datetime.timedelta(seconds=51300), 140.0, 200), ('Bristol', datetime.timedelta(seconds=41400), 'Manchester', datetime.timedelta(seconds=59400), 100.0, 200), ('Manchester', datetime.timedelta(seconds=44400), 'Bristol', datetime.timedelta(seconds=62400), 100.0, 200), ('Bristol', datetime.timedelta(seconds=27600), 'London', datetime.timedelta(seconds=39600), 100.0, 200), ('London', datetime.timedelta(seconds=39600), 'Manchester', datetime.timedelta(seconds=63600), 130.0, 200), ('Manchester', datetime.timedelta(seconds=44400), 'Glasgow', datetime.timedelta(seconds=65400), 130.0, 200), ('Bristol', datetime.timedelta(seconds=27600), 'Glasgow', datetime.timedelta(seconds=47100), 160.0, 200), ('Glasgow', datetime.timedelta(seconds=52200), 'Newcastle', datetime.timedelta(seconds=74700), 130.0, 200), ('Newcastle', datetime.timedelta(seconds=58500), 'Manchester', datetime.timedelta(seconds=75000), 130.0, 200), ('Manchester', datetime.timedelta(seconds=66300), 'Bristol', datetime.timedelta(seconds=84300), 100.0, 200), ('Bristol', datetime.timedelta(seconds=22800), 'Manchester', datetime.timedelta(seconds=40800), 100.0, 200), ('Southampton', datetime.timedelta(seconds=43200), 'Manchester', datetime.timedelta(seconds=70200), 100.0, 200), ('Manchester', datetime.timedelta(seconds=68400), 'Southampton', datetime.timedelta(seconds=9000), 100.0, 200), ('Birmingham', datetime.timedelta(seconds=57600), 'Newcastle', datetime.timedelta(seconds=84600), 130.0, 200), ('Newcastle', datetime.timedelta(seconds=21600), 'Birmingham', datetime.timedelta(seconds=48600), 130.0, 200), ('Aberdeen', datetime.timedelta(seconds=25200), 'Portsmouth', datetime.timedelta(seconds=61200), 130.0, 200)]

I've created a dict that contains unique departing city names as follows:我创建了一个包含唯一出发城市名称的字典,如下所示:

for row in results:
    tempDict.append(row[0])
    departure_cities = dict.fromkeys(tempDict,)
print(departure_cities)

Which prints:哪个打印:

{'Newcastle': None, 'Bristol': None, 'Manchester': None, 'London': None, 'Glasgow': None, 'Southampton': None, 'Birmingham': None, 'Aberdeen': None}

Is there a way for me to populate the above dict with the corresponding arrival locations contained within the SQL statement?有没有办法让我用 SQL 语句中包含的相应到达位置填充上述字典?

Thanks.谢谢。

You can use collections.defaultdict :您可以使用collections.defaultdict

from collections import defaultdict
d = defaultdict(set)
for a, _, b, *_ in results:
   d[a].add(b)

new_result = {a:list(b) for a, b in d.items()}

Output: Output:

{'Newcastle': ['Birmingham', 'Bristol', 'Manchester'], 'Bristol': ['London', 'Manchester', 'Newcastle', 'Glasgow'], 'Manchester': ['Southampton', 'Bristol', 'Glasgow'], 'London': ['Manchester'], 'Glasgow': ['Newcastle'], 'Southampton': ['Manchester'], 'Birmingham': ['Newcastle'], 'Aberdeen': ['Portsmouth']}

Edit: inclusion of departure and arrival times in final result:编辑:在最终结果中包含出发和到达时间:

d = defaultdict(set)
for a, _d, b, arr, *_ in results:
   d[a].add((b, _d, arr))

result = {a:[dict(zip(['destination', 'departure', 'arrival'], i)) for i in b] for a, b in d.items()}

Output: Output:

{'Newcastle': [{'destination': 'Manchester', 'departure': datetime.timedelta(seconds=58500), 'arrival': datetime.timedelta(seconds=75000)}, {'destination': 'Birmingham', 'departure': datetime.timedelta(seconds=21600), 'arrival': datetime.timedelta(seconds=48600)}, {'destination': 'Bristol', 'departure': datetime.timedelta(seconds=60300), 'arrival': datetime.timedelta(seconds=82800)}], 'Bristol': [{'destination': 'Glasgow', 'departure': datetime.timedelta(seconds=27600), 'arrival': datetime.timedelta(seconds=47100)}, {'destination': 'London', 'departure': datetime.timedelta(seconds=27600), 'arrival': datetime.timedelta(seconds=39600)}, {'destination': 'Newcastle', 'departure': datetime.timedelta(seconds=28800), 'arrival': datetime.timedelta(seconds=51300)}, {'destination': 'Manchester', 'departure': datetime.timedelta(seconds=22800), 'arrival': datetime.timedelta(seconds=40800)}, {'destination': 'Manchester', 'departure': datetime.timedelta(seconds=41400), 'arrival': datetime.timedelta(seconds=59400)}], 'Manchester': [{'destination': 'Bristol', 'departure': datetime.timedelta(seconds=44400), 'arrival': datetime.timedelta(seconds=62400)}, {'destination': 'Glasgow', 'departure': datetime.timedelta(seconds=44400), 'arrival': datetime.timedelta(seconds=65400)}, {'destination': 'Southampton', 'departure': datetime.timedelta(seconds=68400), 'arrival': datetime.timedelta(seconds=9000)}, {'destination': 'Bristol', 'departure': datetime.timedelta(seconds=66300), 'arrival': datetime.timedelta(seconds=84300)}], 'London': [{'destination': 'Manchester', 'departure': datetime.timedelta(seconds=39600), 'arrival': datetime.timedelta(seconds=63600)}], 'Glasgow': [{'destination': 'Newcastle', 'departure': datetime.timedelta(seconds=52200), 'arrival': datetime.timedelta(seconds=74700)}], 'Southampton': [{'destination': 'Manchester', 'departure': datetime.timedelta(seconds=43200), 'arrival': datetime.timedelta(seconds=70200)}], 'Birmingham': [{'destination': 'Newcastle', 'departure': datetime.timedelta(seconds=57600), 'arrival': datetime.timedelta(seconds=84600)}], 'Aberdeen': [{'destination': 'Portsmouth', 'departure': datetime.timedelta(seconds=25200), 'arrival': datetime.timedelta(seconds=61200)}]}

You can also form the arrival locations themselves as dictionaries, instead of a list:您还可以将到达位置本身形成为字典,而不是列表:

result = {a:{j:{'departure':k, 'arrival':l} for j, k, l in b} for a, b in d.items()}

Output: Output:

{'Newcastle': {'Manchester': {'departure': datetime.timedelta(seconds=58500), 'arrival': datetime.timedelta(seconds=75000)}, 'Birmingham': {'departure': datetime.timedelta(seconds=21600), 'arrival': datetime.timedelta(seconds=48600)}, 'Bristol': {'departure': datetime.timedelta(seconds=60300), 'arrival': datetime.timedelta(seconds=82800)}}, 'Bristol': {'Glasgow': {'departure': datetime.timedelta(seconds=27600), 'arrival': datetime.timedelta(seconds=47100)}, 'London': {'departure': datetime.timedelta(seconds=27600), 'arrival': datetime.timedelta(seconds=39600)}, 'Newcastle': {'departure': datetime.timedelta(seconds=28800), 'arrival': datetime.timedelta(seconds=51300)}, 'Manchester': {'departure': datetime.timedelta(seconds=41400), 'arrival': datetime.timedelta(seconds=59400)}}, 'Manchester': {'Bristol': {'departure': datetime.timedelta(seconds=66300), 'arrival': datetime.timedelta(seconds=84300)}, 'Glasgow': {'departure': datetime.timedelta(seconds=44400), 'arrival': datetime.timedelta(seconds=65400)}, 'Southampton': {'departure': datetime.timedelta(seconds=68400), 'arrival': datetime.timedelta(seconds=9000)}}, 'London': {'Manchester': {'departure': datetime.timedelta(seconds=39600), 'arrival': datetime.timedelta(seconds=63600)}}, 'Glasgow': {'Newcastle': {'departure': datetime.timedelta(seconds=52200), 'arrival': datetime.timedelta(seconds=74700)}}, 'Southampton': {'Manchester': {'departure': datetime.timedelta(seconds=43200), 'arrival': datetime.timedelta(seconds=70200)}}, 'Birmingham': {'Newcastle': {'departure': datetime.timedelta(seconds=57600), 'arrival': datetime.timedelta(seconds=84600)}}, 'Aberdeen': {'Portsmouth': {'departure': datetime.timedelta(seconds=25200), 'arrival': datetime.timedelta(seconds=61200)}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据其中一个关键值将此连接查询的结果转换为dict? - How can I turn the results from this joined query into dict based on one of the key values? 如何在 Python 中创建字典并使用 SQL 查询的结果填充键和值? - How to create a dictionary and populate the key and values with the results of a SQL query in Python? 如何将 SQL 数据库表中的这些数据转换为 dict? - How do I turn this data from an SQL database table into a dict? 如何从列表和csv文件创建[dict] - How do I create [dict] from a list and csv file 如何从字典中提取和合并值 - How do i extract and combine values from a dict 如何从状态字典创建模型? - How do I create a model from a state dict? Python-使用游标执行SQL查询,如何确定SQL是否有> 0个结果? - Python - use cursor to perform SQL query, how do I find out if there were > 0 results from SQL? 当 dict 值是列表时,如何从 int 获取 dict 键? - How do I get a dict key from an int when the dict values are lists? 如何通过在 python 中的分隔符上拆分键来从 dict 创建嵌套的 dict? - How do I create a nested dict from a dict by splitting the keys on a delimiter in python? 如何从Python中带有嵌套字典的字典中创建新的字典 - How do I create a new dict of dicts from a dict with nested dicts in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM