Mutual conversion between Python strings, lists and dictionaries

In Python programming, we often use data structures such as strings (str), lists (list) and dictionaries (dict), and of course, we often need to involve the mutual conversion of these three types. This article will do my best to introduce the transformation of the above three data structures to everyone in detail.

1. String —> List

1. Use the built-in function list ()

Description: The list() function is a built-in function of Python. It can convert any iterable data to a list type and return the converted list. The list function can create an empty list when the argument is empty.

grammar:

list(object)

object is the data type to be converted to a list.

str = "chenkk zijunjun"
list1 = list(str) #将字符串转化为列表
print(str)
print(list1)
print(type(list1))
#Outout
#chenkk zijunjun
#['c', 'h', 'e', 'n', 'k', 'k', ' ', 'z', 'i', 'j', 'u', 'n', 'j', 'u', 'n']
#<class 'list'>

2. Use the built-in function eval()

Description: The eval() function is used to execute a string expression and return the value of the expression. You can also convert strings into corresponding objects (such as conversion between list, tuple, dict and string)

grammar:

eval(expression[, globals[, locals]])

parameter:

  • expression – the expression.
  • globals – variable scope, global namespace, if provided, must be a dictionary object.
  • locals – variable scope, local namespace, if provided, can be any mapping object.
str = "['chenkk','zijunjun']"
list2 = eval(str)
print(type(list2))
print(list2)
#Outout
#<class 'list'>
#['chenkk', 'zijunjun']

3. Use the built-in module json.loads() method

import json
str = '["chenkk","zijunjun"]'
list3 = json.loads(str)
print(type(list3))
print(list3)
'''json.loads()是将json格式字符串转换为python对象,
而json的标准规范应该使用双引号,单引号会报错。'''
#Outout
#<class 'list'>
#['chenkk', 'zijunjun']

4. Use split() to split

Description: Python split() slices the string by the specified delimiter, if the parameter num has a specified value, separate num+1 substrings. The return is a list.

grammar:

str.split(str="", num=string.count(str))

parameter:

  • str – delimiter, the default is all null characters, including spaces, newlines (\n), tabs (\t), etc.
  • num – the number of splits. Defaults to -1, which separates all.

return value:

Returns a list of split strings.

str = 'chen&kk&zi&jun&jun'
list4 = str.split('&')
print(type(list4))
print(list4)
#Outout
#<class 'list'>
#['chen', 'kk', 'zi', 'jun', 'jun'] 返回分割后的字符串列表

If splitting on multiple characters, the built-in module re.split() method can be used. You can refer to this link I gave to learn more about the methods of the re module

import re
str = "1cat2dogs3cats4"
list5 = re.split(r"\d+",str)
print(type(list5))
print(list5)
#Outout
#<class 'list'>
#['', 'cat', 'dogs', 'cats', '']

The re.split method is not perfect. For example, in the following example, the split string list has more spaces at the beginning and end, which need to be removed manually.

2. List — > String

1. Use the built-in function str()

describe:

The str() function converts an object into a human-readable form.

grammar:

str(object)

parameter:

  • object - the object.
list1 = ['chen', 'kk', 'zi', 'jun', 'jun']
print(list1)
print(type(list1))
print(list1[::-1]) #列表逆序输出
list1 = str(list1)
print(list1)
print(type(list1))
print(list1[::-1])  #字符串逆序输出
#Outout
# ['chen', 'kk', 'zi', 'jun', 'jun']
# <class 'list'>
# ['jun', 'jun', 'zi', 'kk', 'chen']
# ['chen', 'kk', 'zi', 'jun', 'jun']
# <class 'str'>
# ]'nuj' ,'nuj' ,'iz' ,'kk' ,'nehc'[

When comparing lists and strings, the reverse order output of strings and lists is used . Interested students can click this link to learn more.

2. Use join() for splicing

list1 =['username = admin','password = 123456']
print(list1)
print(type(list1))
print('`````````````````')
str1 = ' & '.join(list1)
print(str1)
print(type(str1))

#Outout
# ['username = admin', 'password = 123456']
# <class 'list'>
# `````````````````
# username = admin & password = 123456
# <class 'str'>

3. String — > Dictionary

1. Use the built-in function eval ()

str1 = "{'username':'admin','password':'123456'}"
print(str1)
print(type(str1))
print('``````````````')
dict1 = eval(str1)
print(type(dict1))
print(dict1)

#Outout
# {'username':'admin','password':'123456'}
# <class 'str'>
# ``````````````
# <class 'dict'>
# {'username': 'admin', 'password': '123456'}

Here is a brief talk about my experience in using the eval() function. When the input format is determined, this function can convert the statements in the function into the data type we originally thought of when inputting the data and return it. Although it is easy to use, but It is not easy to evaluate the effect in actual application, and here we only use it for understanding.

4. Dictionary — > String

Use the built-in function str()

dict1 = {
    
    'username': 'admin', 'password': '123456'}
str1 =str(dict1)
print(type(str1))
print(str1)

#Outout
#<class 'str'>
# {'username': 'admin', 'password': '123456'}

5. Dictionary — > List

Use the built-in function list()

dict1 = {
    
    'username': 'admin', 'password': '123456'}
print(type(dict1))
print('````````````')
list1 = list(dict1)
print(type(list1))
print(list1)
print('````````````')
list2 = list(dict1.values()) #取到字典的键值
print((type(list2)))
print(list2)

#Outout
# <class 'dict'>
# ````````````
# <class 'list'>
# ['username', 'password']
# ````````````
# <class 'list'>
# ['admin', '123456']

6. List — > Dictionary

1. Use the built-in function doct() to convert the nested list into a dictionary

list1 = [['a',1],['b',2],['c',True]]
dict1 = dict(list1)
print(type(dict1))
print(dict1)

#Outout
#<class 'dict'>
#{'a': 1, 'b': 2, 'c': True}

2. Use the built-in function zip() to convert the two lists into dictionaries

list1 = ['a','b','c','d','e']
list2 = ['1','2','3','4','5']
dict1 = dict(zip(list1,list2))
print(type(dict1))
print(dict1)

#Outout
#<class 'dict'>
#{'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5'}

If the lengths of the two lists are not the same, the extra elements will not be displayed.

list1 = ['a','b','c','d','e']
list2 = ['1','2','3']
dict1 = dict(zip(list1,list2))
print(type(dict1))
print(dict1)

#Outout
#<class 'dict'>
#{'a': '1', 'b': '2', 'c': '3'}

Guess you like

Origin blog.csdn.net/chenjh027/article/details/128176581