简体   繁体   English

python '双重理解' 列表到 dict

[英]python 'double comprehension' list to dict

Given a data structure ' posts ' like the following, is there a pythonesque/dict comprehension/efficient way of creating a dict with each of the ids as keys to the posts:给定如下的数据结构“帖子”,是否有一种 pythonesque/dict 理解/有效的方法来创建一个 dict,其中每个 id 作为帖子的键:

posts = [{"ids":[1,2],...}, {"ids":[5, 6, 7], ...},...]
want = {1: {"ids":[1,2],..}, 2:{"ids":[1,2],...}, 5: {"ids":[5,6,7],...}, 6:{"ids":[5,6,7],..}, ...}

# long way
d = {}
for post in posts:
    for id in post['ids']:
        d[id] = post

# one comprehension - dicts created and disposed on each loop
d = {}
for post in posts:
    d.update({id: post for id in post['ids']})

I would hope the following would work - but the top level doesn't see the bottom level post我希望以下内容可行-但顶层看不到底层帖子

# ilegal: post not available 
d = {id: post for id in post['ids'] for post in posts}

Any ideas?有任何想法吗? I see cases like this frequently and the loop seems ugly我经常看到这样的情况,而且循环看起来很丑

You can use a dictionary comprehension:您可以使用字典理解:

posts = [{"ids":[1,2]}, {"ids":[5, 6, 7]}]
result = {i:b for b in posts for i in b['ids']}

Output: Output:

{1: {'ids': [1, 2]}, 2: {'ids': [1, 2]}, 5: {'ids': [5, 6, 7]}, 6: {'ids': [5, 6, 7]}, 7: {'ids': [5, 6, 7]}}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM