在 Python 中将列表字符串转换为字典
pythonserver side programmingprogramming更新于 2026/1/22 8:44:17
这里我们有一个场景,如果字符串包含元素,则使其成为列表。但这些元素也可以表示键值对,使其成为字典。在本文中,我们将了解如何获取这样的列表字符串并将其转换为字典。
使用拆分和切片
在这种方法中,我们使用拆分函数将元素分离为键值对,并使用切片将键值对转换为字典格式。
示例
stringA = '[Mon:3, Tue:5, Fri:11]'
# 给定字符串
print("给定字符串:\n",stringA)
# 类型检查
print(type(stringA))
# 使用 split
res = {sub.split(":")[0]: sub.split(":")[1] for sub in stringA[1:-1].split(", ")}
# 结果
print("The converted dictionary : \n",res)
# 类型检查
print(type(res))
输出
运行上述代码得到以下结果 −
('Given string : \n', '[Mon:3, Tue:5, Fri:11]')
('The converted dictionary : \n', {'Fri': '11', 'Mon': '3', 'Tue': '5'})
使用 eval 和 replace
eval 函数可以从字符串中获取实际列表,然后 replace 将每个元素转换为键值对。
示例
stringA = '[18:3, 21:5, 34:11]'
# 给定字符串
print("给定字符串:\n",stringA)
# 类型检查
print(type(stringA))
# 使用 eval
res = eval(stringA.replace("[", "{").replace("]", "}"))
# 结果
print("转换后的字典 :\n",res)
# 类型检查
print(type(res))
输出
运行上述代码得到以下结果 −
('给定字符串:\n','[18:3, 21:5, 34:11]')
('转换后的字典:\n',{18: 3, 34: 11, 21: 5})
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

