将字符串元组转换为dict [英] Convert string tuples to dict

查看:103
本文介绍了将字符串元组转换为dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串格式错误:

a = '(a,1.0),(b,6.0),(c,10.0)'

我需要dict:

d = {'a':1.0, 'b':6.0, 'c':10.0}

我尝试:

print (ast.literal_eval(a))
#ValueError: malformed node or string: <_ast.Name object at 0x000000000F67E828>

然后我尝试将char替换为'string dict',这很丑陋,并且不起作用:

Then I try replace chars to 'string dict', it is ugly and does not work:

b = a.replace(',(','|{').replace(',',' : ')
     .replace('|',', ').replace('(','{').replace(')','}')
print (b)
{a : 1.0}, {b : 6.0}, {c : 10.0}

print (ast.literal_eval(b))
#ValueError: malformed node or string: <_ast.Name object at 0x000000000C2EA588>

你做什么工作?缺少什么?可以使用regex吗?

What do you do? Something missing? Is possible use regex?

推荐答案

鉴于字符串具有上述格式,您可以将正则表达式替换为 backrefs

Given the string has the above stated format, you could use regex substitution with backrefs:

import re

a = '(a,1.0),(b,6.0),(c,10.0)'
a_fix = re.sub(r'\((\w+),', r"('\1',",a)

因此,您要寻找模式(x,(其中x\w的序列,然后将其替换为('x',.结果为:

So you look for a pattern (x, (with x a sequence of \ws and you substitute it into ('x',. The result is then:

# result
a_fix == "('a',1.0),('b',6.0),('c',10.0)"

然后解析a_fix并将其转换为dict:

and then parse a_fix and convert it to a dict:

result = dict(ast.literal_eval(a_fix))

当时的结果:

>>> dict(ast.literal_eval(a_fix))
{'b': 6.0, 'c': 10.0, 'a': 1.0}

这篇关于将字符串元组转换为dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆