Search code examples
pythonpython-3.xlist-comprehensioniterable-unpackingpep448

Weird unpacking in list comprehension


I was watching a lecture from David Beazley. At minute 23:20 he does some "magic" with unpacking that I am having hard time understanding.

The "magic line" is

fail = [ { **row, 'DBA Name': row['DBA Name'].replace("'",'').upper() } for row in fail ]

I have searched for similar examples but I couldn't find any. Can you explain what is going on in this code? Can you point me to some similar examples?


Solution

  • The snippet is unpacking an already existing mapping row in a dictionary literal while adding a new element. A simplified example demonstrating this:

    >>> r = {'a':1, 'b':2}    
    >>> {**r, 'Spam': 20}
    {'Spam': 20, 'a': 1, 'b': 2}
    

    This unpacking is only available in Pythons >= 3.5 as introduced with PEP 448; in previous versions it is a SyntaxError.