Create a dictionary with list comprehension

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

    Try this,

    def get_dic_from_two_lists(keys, values):
        return { keys[i] : values[i] for i in range(len(keys)) }
    

    Assume we have two lists country and capital

    country = ['India', 'Pakistan', 'China']
    capital = ['New Delhi', 'Islamabad', 'Beijing']
    

    Then create dictionary from the two lists:

    print get_dic_from_two_lists(country, capital)
    

    The output is like this,

    {'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}
    
    0 讨论(0)
  • 2020-11-21 08:08

    In Python 2.7, it goes like:

    >>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
    >>> dict( zip( list1, list2))
    {'a': 1, 'c': 3, 'b': 2}
    

    Zip them!

    0 讨论(0)
提交回复
热议问题