multiple key value pairs in dict comprehension

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)