python 列表中字典转化为字符串_在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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值