Create a dictionary with list comprehension

前端 未结 14 1992
灰色年华
灰色年华 2020-11-21 07:07

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydi         


        
14条回答
  •  甜味超标
    2020-11-21 08:05

    Create a dictionary with list comprehension in Python

    I like the Python list comprehension syntax.

    Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

    mydict = {(k,v) for (k,v) in blah blah blah}
    

    You're looking for the phrase "dict comprehension" - it's actually:

    mydict = {k: v for k, v in iterable}
    

    Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

    blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]
    

    Dict comprehension syntax:

    Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudo-code approximates) is the colon, : like below:

    mydict = {k: v for k, v in blahs}
    

    And we see that it worked, and should retain insertion order as-of Python 3.7:

    >>> mydict
    {'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}
    

    In Python 2 and up to 3.6, order was not guaranteed:

    >>> mydict
    {'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}
    

    Adding a Filter:

    All comprehensions feature a mapping component and a filtering component that you can provide with arbitrary expressions.

    So you can add a filter part to the end:

    >>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
    >>> mydict
    {'blah0': 'blah', 'blah2': 'blah'}
    

    Here we are just testing for if the last character is divisible by 2 to filter out data before mapping the keys and values.

提交回复
热议问题