Create a dictionary with list comprehension

前端 未结 14 1999
灰色年华
灰色年华 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:06

    Here is another example of dictionary creation using dict comprehension:

    What i am tring to do here is to create a alphabet dictionary where each pair; is the english letter and its corresponding position in english alphabet

    >>> import string
    >>> dict1 = {value: (int(key) + 1) for key, value in 
    enumerate(list(string.ascii_lowercase))}
    >>> dict1
    {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
    'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
    19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
    >>> 
    

    Notice the use of enumerate here to get a list of alphabets and their indexes in the list and swapping the alphabets and indices to generate the key value pair for dictionary

    Hope it gives a good idea of dictionary comp to you and encourages you to use it more often to make your code compact

提交回复
热议问题