Skip to content

Python dictionary comprehension multiple keys

  • by

Python dictionary comprehension of multiple keys is not allowed. The comprehension format is strictly limited to one result per iteration. You can add extra loops though, to loop over the multiple elements you want to insert:

{k: v for k1, k2, v1, v2 in data for k, v in ((k1, v1), (k2, v2))}

or your second example:

{k: v for k1, k2, v, _ in data for k in (k1, k2)}

which is the equivalent of:

result = {}
for k1, k2, v1, v2 in data:
    for k in (k1, k2):
        result[k] = v

Python dictionary comprehension of multiple keys

Simple example code. A dictionary comprehension can only ever produce one key-value pair per iteration. The trick is to produce an extra loop to separate the pairs using the zip function.

wp_users = [(1, 'Bill'), (2, 'Bob')]
d = {k: v for e in wp_users for k, v in zip(('ID', 'post_author'), e)}



Comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *