Create a dictionary with list comprehension

前端 未结 14 2035
灰色年华
灰色年华 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'}
    

提交回复
热议问题