multiple key value pairs in dict comprehension

mdxprograms picture mdxprograms · Jun 1, 2014 · Viewed 24k times · Source

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?

Answer

Martijn Pieters picture Martijn Pieters · Sep 12, 2014

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