Python将一个偶数字符串转换为dict [英] Python convert a paritcular string to dict

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

问题描述

字符串的格式类似于"a:1 b:2 c:x d:2.13e-5",有什么方法可以快速,简单地将其转换为python dict?

The format of string is like "a:1 b:2 c:x d:2.13e-5", is there some way to convert it to python dict quickly and simply?

--------------编辑行--------------

-------------- edit line --------------

根据很好的答案,我尝试了几种方法(在ipython中):

According the great answers, I tried several methods (in ipython):

In [6]: import re

In [7]: %paste
def f1(line):
    item_dict = {}
    for item in line.split():
        kv = item.split(':')
        item_dict[kv[0]] = kv[1]

def f2(line):
    item_dict = {}
    item_pat = re.compile(r'(\w+):(.+)')
    for item in line.split():
        m_res = item_pat.match(item)
        item_dict[m_res.group(1)] = m_res.group(2)

def f3(line):
    dict(item.split(':') for item in line.split())
## -- End pasted text --

In [8]: line = 'a:1   b:3243 dsfds:4323llsjdf         \t fdsf:3232l'
In [9]: %timeit f1(line)
100000 loops, best of 3: 3.99 us per loop

In [10]: %timeit f2(line)
100000 loops, best of 3: 8.83 us per loop

In [11]: %timeit f3(line)
100000 loops, best of 3: 5.19 us per loop

第一个方法f1()似乎更快,但是在我的应用程序中,它仍然花费大量时间(约占总数的30%),因为它被调用了数百万次.

The first method f1() seems faster, but in my application, it still use much time(about 30% of all) because it's invoked millions of times.

还有其他更有效的方法吗?还是cython?

Are there any more effective ways? Or cython?

推荐答案

import ast

def guess(s):
    try:
        return ast.literal_eval(s)
    except ValueError:
        return s    

s = "a:1 b:2 c:x d:2.13e-5"
print dict(map(guess, x.split(':')) for x in s.split())


{'a': 1, 'c': 'x', 'b': 2, 'd': 2.13e-05}

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

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