[英]Python convert a paritcular string to dict
The format of string is like "a:1 b:2 c:xd:2.13e-5"
, is there some way to convert it to python dict quickly and simply? 字符串的格式类似于"a:1 b:2 c:xd:2.13e-5"
,是否有某种方法可以快速,简单地将其转换为python dict?
-------------- edit line -------------- --------------编辑行--------------
According the great answers, I tried several methods (in ipython): 根据很好的答案,我尝试了几种方法(在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
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. 第一种方法f1()
似乎更快,但是在我的应用程序中,它仍然使用很多时间(约占总数的30%),因为它被调用了数百万次。
Are there any more effective ways? 有没有更有效的方法? Or cython
? 还是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'}
This split
s the string, first by spaces, to get the key-value pairs ( p
). 此操作首先将字符串split
为空格,以获取键值对( p
)。 Then it splits each pair by ':' to yield each key/value to be added to the dictionary. 然后,将每个对用“:”分隔,以产生要添加到字典中的每个键/值。
Note that no conversion has taken place. 请注意,未进行任何转换。 All keys/values are still strings. 所有键/值仍然是字符串。 To do any better than this, you're going to need a somewhat smart function that will convert any input string into your expected types. 为了做得更好,您将需要一个稍微聪明的函数,该函数会将任何输入字符串转换为您期望的类型。
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.