Home  >  Article  >  Backend Development  >  How to convert a list into a dictionary in python

How to convert a list into a dictionary in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-12 17:53:5119099browse

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:

How to convert a list into a dictionary in python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn