1. Now there are two lists, List1 = [' Key1 ', ' key2 ', ' Key3 '] and list2 = [' 1 ', ' 2 ', ' 3 '], convert them into such dictionaries: {' key1 ': ' 1 ', ' key2 ': ' 2 ', ' Key3 ': ' 3 '}
>>>list1 = [' Key1 ', ' key2 ', ' Key3 ']
>>>list2 = [' 1 ', ' 2 ', ' 3 ']
>>>dict (Zip (list1,list2))
{' Key1 ': ' 1 ', ' key2 ': ' 2 ', ' Key3 ': ' 3 '}
2, the nested list into a dictionary, there are two ways,
>>>new_list= [[' Key1 ', ' value1 '],[' key2 ', ' value2 '],[' Key3 ', ' value3 ']
>>>dict (list)
{' Key3 ': ' Value3 ', ' key2 ': ' value2 ', ' key1 ': ' value1 '}
or this:
>>>new_list= [[' Key1 ', ' value1 '],[' key2 ', ' value2 '],[' Key3 ', ' value3 ']
>>>new_dict = {}
>>> for I in New_list:
... new_dict[i[0]] = i[1] #字典赋值, key on the left, value on right
...
>>> new_dict
{' Key3 ': ' Value3 ', ' key2 ': ' value2 ', ' key1 ': ' value1 '}
Two small ways to convert a Python list to a dictionary