Python如何将字符串字典转换为字典?

2021年4月24日13:04:13 发表评论 780 次浏览

数据类型的相互转换已经讨论了很多次, 并且已经成为一个非常普遍的问题。本文讨论了将字符串格式转换为字典的字典互转换的另一个问题。让我们讨论实现此目的的某些方法。

方法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}

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: