简体   繁体   中英

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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