Python 3.x 通过python协同程序生成dict结果,就像node.js async.parallel一样

Python 3.x 通过python协同程序生成dict结果,就像node.js async.parallel一样,python-3.x,python-asyncio,Python 3.x,Python Asyncio,我想用python编写一个dict,如下面的node.js代码: async=require('async'); 异步并行({ html:(完成)=>{ //从url获取html html='html代码…' 完成(空,html) }, 数据:(完成)=>{ //从数据库获取数据 数据=[ { id:1, 名字:“杰”, }, { id:2, 姓名:“John”, } ] 完成(空,数据) }, },(错误,结果)=>{ log('html',result.html) console.log('

我想用python编写一个dict,如下面的node.js代码:

async=require('async');
异步并行({
html:(完成)=>{
//从url获取html
html='html代码…'
完成(空,html)
},
数据:(完成)=>{
//从数据库获取数据
数据=[
{
id:1,
名字:“杰”,
},
{
id:2,
姓名:“John”,
}
]
完成(空,数据)
},
},(错误,结果)=>{
log('html',result.html)
console.log('data',result.data)
});
上面的代码执行两个并行任务,并返回包含带有“html”和“data”标记的键的结果

我想在pytnon中做同样的事情,但我不知道如何通过asyncio实现,请参阅以下代码:

导入异步IO
异步def get_html():
等待asyncio.sleep(1)
html='html代码…'
返回html
异步def get_data():
等待asyncio.sleep(1)
数据=[
{
“id”:1,
'姓名':'杰伊',
},
{
“id”:2,
“姓名”:“乔恩”,
}
]
返回数据
异步def main():
任务=[get_html(),get_data()]
结果=等待asyncio.gather(*任务)
打印(键入(结果))#但这是一个列表
#结果['html']#我希望它包含带有'html'和'data'的键
#结果['data']
打印(结果[0])#我不知道哪个是html
打印(结果[1])#哪些是数据
loop=asyncio.get\u event\u loop()
循环。运行\u直到完成(main())
loop.close()

提前感谢!:)

首先,您应该将
wait
asyncio.sleep()一起使用

您可以使用以下功能-作者的学分:


这将并行执行两个协同程序并打印:
{'html':'html code…','data':[{'id':1,'name':'Jay'},{'id':2,'name':'Jonh'}}

谢谢!和我想的一样
async def gather_dict(tasks: dict):
    async def mark(key, coro):
        return key, await coro

    return {
        key: result
        for key, result in await gather(
            *(mark(key, coro) for key, coro in tasks.items())
        )
    }

async def main():
    result = await gather_dict({'html': get_html(), 'data': get_data()})
    print(result)