When processing data, it is often necessary to convert the format of the data to facilitate operations such as data traversal. Let's take a look at several data type conversions in Python.
1. Convert string to dictionary:
dict_string = "{'name':'linux','age':18}" to_dict = eval(dict_string) print(type(to_dict))
You can also use json for conversion
import json #如果是Python2.6应该是simplejson dict_string = "{'name':'linux','age':18}" to_dict = json.loads(dict_string.replace("\‘","\“")) #这里需要将字符串的单引号转换成双引号,不然json模块会报错的 print(type(to_dict))
2. Convert dictionary to string
Similarly You can use json
import json dict_1 = {'name':'linux','age':18} dict_string = json.dumps(dict_1) print(type(dict_string))
Of course, you can also directly use str to force conversion
dict_1 = {'name':'linux','age':18} dict_string = str(dict_1) print(type(dict_string))
3. String to list
Specify the delimiter
string1 = "1,2,3,4,5,'aa',12" print(type(string1.split(',')))
If it is already List format, just use eval directly
string2 = "[1,2,3,4,5,'aa',12]" print(type(eval(string2)))
4. Convert list to string
Use str directly to force conversion
print(type(str([1, 2,3,4,5,'aa',12])))
Specify the separator. Note that the lists here need to be of string type, otherwise an error will be reported during splicing
print(type("--".join(['a','b','c'])))
5. Convert list to dictionary
Two List, list1 = ['k1','k2','k3'], list2 = [1,2,3], converted into dictionary {'k1':1,'k2':2,'k3':3}
list1 = ['k1','k2','k3'] list2 = [1,2,3] print(dict(zip(list1,list2)))
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to convert data types in python. For more information, please follow other related articles on the PHP Chinese website!