📜  Python|将字符串字典转换为字典

📅  最后修改于: 2022-05-13 01:55:22.980000             🧑  作者: Mango

Python|将字符串字典转换为字典

数据类型的相互转换已经被讨论过很多次,并且一直是一个非常受欢迎的问题。本文讨论了字典相互转换的另一个问题,从字符串格式到字典。让我们讨论一些可以做到这一点的方法。

方法 #1:使用json.loads()

使用Python的 json 库加载的内置函数可以轻松执行此任务,该函数将有效字典的字符串转换为 json 格式, Python中的字典。

# Python3 code to demonstrate
# convert dictionary string to dictionary
# using json.loads()
import json
  
# initializing string 
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}' 
  
# printing original string 
print("The original string : " + str(test_string))
  
# using json.loads()
# convert dictionary string to dictionary
res = json.loads(test_string)
  
# print result
print("The converted dictionary : " + str(res))
输出 :
The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}

方法 #2:使用ast.literal_eval()

上述方法也可用于执行类似的转换。该函数比 eval函数更安全,也可用于字典以外的所有数据类型的相互转换。

# Python3 code to demonstrate
# convert dictionary string to dictionary
# using ast.literal_eval()
import ast
  
# initializing string 
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}' 
  
# printing original string 
print("The original string : " + str(test_string))
  
# using ast.literal_eval()
# convert dictionary string to dictionary
res = ast.literal_eval(test_string)
  
# print result
print("The converted dictionary : " + str(res))
输出 :
The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}
The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}