41

I found the following stack overflow post about dict comprehensions in Python2.7 and Python 3+: Create a dictionary with list comprehension in Python stating that I can apply dictionary comprehensions like this:

d = {key: value for (key, value) in sequence}

I tried it in Python 3. However, it raises an exception.

d = {'a':1, 'b':2, 'c':3, 'd':4}
{key : value for (key, value) in d}
{key : value for key, value in d}

Both versions raise a ValueError saying that ValueError: need more than 1 value to unpack.

What is the easiest / the most direct way to make a dictionary comprehension in Python3?

Community
  • 1
  • 1
Jon
  • 11,356
  • 5
  • 40
  • 74
  • 3
    That dict comprehension expects a sequence of key-value pairs. You are feeding it a dict, which is not a sequence of key-value pairs. – user2357112 Dec 10 '13 at 08:42
  • I know that this is an old question, but I just wanted to add that to avoid the error, `d` should be `(('a', 1), ('b', 2), ('c', 3'), ('d', 4))` – Artemis Apr 21 '19 at 20:36

3 Answers3

71

Looping over a dictionary only yields the keys. Use d.items() to loop over both keys and values:

{key: value for key, value in d.items()}

The ValueError exception you see is not a dict comprehension problem, nor is it limited to Python 3; you'd see the same problem in Python 2 or with a regular for loop:

>>> d = {'a':1, 'b':2, 'c':3, 'd':4}
>>> for key, value in d:
...     print key, value
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

because each iteration there is only one item being yielded.

Without a transformation, {k: v for k, v in d.items()} is just a verbose and costly d.copy(); use a dict comprehension only when you do a little more with the keys or values, or use conditions or a more complex loop construct.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
11

Well said above - you can drop items in Python3 if you do it this way:

{key: d[key] for key in d}

d = {'a':1, 'b':2, 'c':3, 'd':4}
z = {x: d[x] for x in d}
z
>>>{'a': 1, 'b': 2, 'c': 3, 'd': 4}

and this provides for the ability to use conditions as well

y = {x: d[x] for x in d if d[x] > 1}
y
>>>{'b': 2, 'c': 3, 'd': 4}

Enjoy!

RandallShanePhD
  • 5,406
  • 2
  • 20
  • 30
1

Dictionary comprehension means generating items in the dictionary by some logic:

x = {p: p*p for p in range(10)}

print(x)

y = {q: q*3 for q in range(5,15) if q%2!=0}

print(y)