Home > Article > Backend Development > How to convert a list into a dictionary in python
Now there is a list, list1 = ['key1','key2','key3'], convert it into a dictionary like this: {'key1':'1','key2':'2',' key3':'3'}
Two methods for python to convert a list into a dictionary:
1. Method: Construct a list again list2 = [' 1','2','3'], after using zip to convert to a tuple, then convert the tuple to a dictionary.
Related recommendations: "Python Video Tutorial"
list1 = ['key1','key2','key3'] list2 = ['1','2','3'] dict(zip(list1,list2)) {'key1':'1','key2':'2','key3':'3'}
2. There are two methods to convert nested lists into dictionaries,
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,右边为value new_dict {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
The above is the detailed content of How to convert a list into a dictionary in python. For more information, please follow other related articles on the PHP Chinese website!