python 字符串str与字典dict转换

发布时间 2023-10-27 09:04:56作者: liwenchao1995

python 字符串str与字典dict转换

字典转字符串

c = {'a': '1', 'b': '1'}
b=str(c)
print(b,type(b))

字符串转字典

字符串转字典分两种情况,需要根据你的字符串内容是否带引号决定,如

# 带引号
c = {'a': '1', 'b': '1'}
#不带引号
c = {a: 1, b: 1}

带引号

带引号的可以用json处理将字符串转成字典,下面案例的str是从一个文件中获取,也可以直接赋值

import json
#a = '{"a":"1", "b":"1"}'
with open(f".aaa.txt","r") as f:
	a = f.readline().strip()
	c=json.loads(a)
	print(c, type(c))

不带引号

不带引号的可以用ast处理

import ast
a = {a:1, b:1}
c=ast.literal_eval(a)
print(c, type(c))