[英]Python convert a paritcular string to dict
字符串的格式类似于"a:1 b:2 c:xd:2.13e-5"
,是否有某种方法可以快速,简单地将其转换为python dict?
--------------编辑行--------------
根据很好的答案,我尝试了几种方法(在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%),因为它被调用了数百万次。
有没有更有效的方法? 还是cython
?
>>> s = "a:1 b:2 c:x d:2.13e-5"
>>> dict( p.split(':') for p in s.split(' ') )
{'a': '1', 'c': 'x', 'b': '2', 'd': '2.13e-5'}
此操作首先将字符串split
为空格,以获取键值对( p
)。 然后,将每个对用“:”分隔,以产生要添加到字典中的每个键/值。
请注意,未进行任何转换。 所有键/值仍然是字符串。 为了做得更好,您将需要一个稍微聪明的函数,该函数会将任何输入字符串转换为您期望的类型。
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.