Python – 将字符串转换为字典列表
给定字符串格式的字典列表,转换为实际的字典列表。
Input : test_str = [“[{‘Gfg’ : 3, ‘Best’ : 8}, {‘Gfg’ : 4, ‘Best’ : 8}]”]
Output : [[{‘Gfg’: 3, ‘Best’: 8}, {‘Gfg’: 4, ‘Best’: 8}]]
Explanation : String converted to list of dictionaries.
Input : test_str = [“[{‘Gfg’ : 3, ‘Best’ : 8}]”]
Output : [[{‘Gfg’: 3, ‘Best’: 8}]]
Explanation : String converted to list of dictionaries.
方法 #1:使用 json.loads() + replace()
上述功能的组合可以用来解决这个问题。在此,我们使用 replace() 替换内部字符串,并使用loads() 创建字典列表。
Python3
# Python3 code to demonstrate working of
# Convert String to List of dictionaries
# Using json.loads + replace()
import json
# initializing string
test_str = ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 9}]"]
# printing original string
print("The original string is : " + str(test_str))
# replace() used to replace strings
# loads() used to convert
res = [json.loads(idx.replace("'", '"')) for idx in test_str]
# printing result
print("Converted list of dictionaries : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert String to List of dictionaries
# Using json.loads + replace()
# initializing string
test_str = "[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]"
# printing original string
print("The original string is : " + str(test_str))
# eval() used to convert
res = list(eval(test_str))
# printing result
print("Converted list of dictionaries : " + str(res))
输出
The original string is : ["[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 4, 'Best' : 9}]"]
Converted list of dictionaries : [[{'Gfg': 3, 'Best': 8}, {'Gfg': 4, 'Best': 9}]]
方法 #2:使用 eval()
这是可以执行此任务的方式之一。 eval() 在内部评估数据类型并返回所需的结果。
Python3
# Python3 code to demonstrate working of
# Convert String to List of dictionaries
# Using json.loads + replace()
# initializing string
test_str = "[{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]"
# printing original string
print("The original string is : " + str(test_str))
# eval() used to convert
res = list(eval(test_str))
# printing result
print("Converted list of dictionaries : " + str(res))
输出
The original string is : [{'Gfg' : 3, 'Best' : 8}, {'Gfg' : 9, 'Best' : 9}]
Converted list of dictionaries : [{'Gfg': 3, 'Best': 8}, {'Gfg': 9, 'Best': 9}]