How to convert a list into a dictionary in python

爱喝马黛茶的安东尼
Release: 2019-06-20 10:09:34
Original
19158 people have browsed it

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'}
Copy after login

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'}
Copy after login

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'}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!