下面是SqlAlchemyselect
操作符的输出。
| device_id | event_name | event_count |
| :--------:| :-----------------: |:-----------:|
| 123456 | speed more than 100 | 3 |
| 123456 | speed less than 12 | 0 |
| 334455 | out of NYC | 5 |
| 111111 | in UCSD campus | 1 |
现在,我想将这个结果保存到一个嵌套字典中,格式如下,但我不知道如何高效地完成。
我需要一个字典,其中键是device_id
,值是字典,其中键是event_name
,值是event_count
。
{'123456' : {'speed more than 100' : 3,
'speed less than 12': 0},
'334455' : {'out of NYC' : 5},
'111111' : {'in UCSD campus' : 1}
}
这是我的代码。
def count_per_event_json(self, count_per_event_query_result):
result = {}
print(count_per_event_query_result)
for item in enumerate(count_per_event_query_result):
if item[0] not in result.keys():
# result[item[0]] = {I don't know how to fill this inner dict'}
return result
我还计算了输入参数并将其传递给函数,如下所示:
def count_per_event(self):
count_per_event_query = select(EventsModel.device_id, EventsModel.event_name,
func.count(EventsModel.rule_table_id)) \
.where(EventsModel.timestamp <= self.max_utc_timestamp) \
.where(EventsModel.timestamp >= self.min_utc_timestamp) \
.group_by(EventsModel.device_id, EventsModel.rule_table_id) \
.execution_options(synchronize_session="fetch")
return count_per_event_query
async def cube_calculator(self):
async with async_session() as session:
count_per_event_query_result = await session.execute(self.count_per_event())
json = self.count_per_event_json(count_per_event_query_result) # the type of count_per_event_query is <class 'sqlalchemy.engine.result.ChunkedIteratorResult'>
1条答案
按热度按时间krcsximq1#
您可以使用pandas执行此操作: