Dictionary Comprehension in Python 3

前端 未结 3 736
一生所求
一生所求 2020-12-05 13:25

I found the following stack overflow post about dict comprehensions in Python2.7 and Python 3+: Create a dictionary with list comprehension in Pyth

3条回答
  •  北海茫月
    2020-12-05 13:42

    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 "", line 1, in 
    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.

提交回复
热议问题