pythonlistcycle

How do I write a one-line generator for this Python 3.x list cycle?


How to make a generator of this cycle correctly?

I am a novice programmer, do not judge strictly, the Mentor asks me to write this cycle in one line

for post in posts:
    post_id_detail[post['id']] = post

I do this but it doesn't work

post = [post_id_detail[post['id']] for post in posts]

Help to make the right generator in one line


Solution

  • post_id_detail is apparently a dict rather than a list, so use a dict comprehension instead:

    post_id_detail = {post['id']: post for post in posts}