在Python中将列表字符串转换为字典
在这里,我们有一个场景,如果呈现的字符串中包含元素,则将其作为列表。但是这些元素也可以表示一个键值对,使其成为字典。在本文中,我们将看到如何采用这样的列表字符串并将其设置为字典。
带分割和切片
在这种方法中,我们使用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替换
eval函数可以从字符串中获取实际列表,然后执行替换操作会将每个元素转换为键值对。
示例
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})热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便