在Python中将列表字符串转换为字典
这里我们有这样一种情况:如果一个字符串包含的元素使其成为一个列表,但这些元素也可以表示一个键值对,使其成为一个字典。在本文中,我们将展示如何使用这样的列表字符串并将其变成一个字典。
使用 split 和 slicing
在此方法中,我们使用 split 函数将元素分隔为键值对,并使用切片将键值对转换为字典格式。
示例
stringA = '[Mon:3, Tue:5, Fri:11]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using split
res = {sub.split(":")[0]: sub.split(":")[1] for sub in stringA[1:-1].split(", ")}
# Result
print("The converted dictionary : \n",res)
# Type check
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]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using eval
res = eval(stringA.replace("[", "{").replace("]", "}"))
# Result
print("The converted dictionary : \n",res)
# Type check
print(type(res))输出
运行以上代码,我们得到以下结果 -
('Given string : \n', '[18:3, 21:5, 34:11]')
('The converted dictionary : \n', {18: 3, 34: 11, 21: 5})
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP