Answer a question

I am trying to create multiple key : value pairs in a dict comprehension like this:

{'ID': (e[0]), 'post_author': (e[1]) for e in wp_users}

I am receiving "missing ','"

I have also tried it this way:

[{'ID': (e[0]), 'post_author': (e[1])} for e in wp_users]

I then receive "list indices must be integers, not str"

Which I understand, but not sure the best way in correcting this and if multiple key : value pairs is possible with dict comprehensions?

Answers

A dictionary comprehension can only ever produce one key-value pair per iteration. The trick then is to produce an extra loop to separate out the pairs:

{k: v for e in wp_users for k, v in zip(('ID', 'post_author'), e)}

This is equivalent to:

result = {}
for e in wp_users:
    for k, v in zip(('ID', 'post_author'), e):
        result[k] = v

Note that this just repeats the two keys with each of your wp_users list, so you are continually replacing the same keys with new values! You may as well just take the last entry in that case:

result = dict(zip(('ID', 'post_author'), wp_users[-1]))

You didn’t share what output you expected however.

If the idea was to have a list of dictionaries, each with two keys, then you want a list comprehension of the above expression applied to each wp_users entry:

result = [dict(zip(('ID', 'post_author'), e)) for e in wp_users]

That produces the same output as your own, second attempt, but now you have a list of dictionaries. You’ll have to use integer indices to get to one of the dictionaries objects or use further loops.

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐