Convert a string with 2-tier delimiters into a dic

2020-04-26 23:36发布

Given a string:

s = 'x\t1\ny\t2\nz\t3'

I want to convert into a dictionary:

sdic = {'x':'1','y':'2','z':'3'}

I got it to work by doing this:

sdic = dict([tuple(j.split("\t")) for j in [i for i in s.split('\n')]])

First: ['x\t1','y\t2','z\t3'] # str.split('\n')

Then: [('x','1'),('y','2'),('z','3')] # tuples([str.split('\t')])

Finally: {'x':'1', 'y':'2', 'z':'3'} # dict([tuples])

But is there a simpler way to convert a string with 2-tier delimiters into a dictionary?

3条回答
Animai°情兽
2楼-- · 2020-04-27 00:25

You're a little verbose in your walking through list comprehensions:

>>> s = 'x\t1\ny\t2\nz\t3'
>>> dd = dict(ss.split('\t') for ss in s.split('\n'))
>>> dd
{'x': '1', 'y': '2', 'z': '3'}
>>>
查看更多
神经病院院长
3楼-- · 2020-04-27 00:39
>>> s = 'x\t1\ny\t2\nz\t3'
>>> spl = s.split()
>>> dict(zip(*[iter(spl)]*2))
{'y': '2', 'x': '1', 'z': '3'}

str.split() takes care of all type of white-space characters. If the delimiters were * and $ for example, then you could use re.split:

>>> import re
>>> s = 'x*1$y*2$z*3'
>>> spl = re.split(r'[*$]{1}', s)
>>> dict(zip(*[iter(spl)]*2))
{'y': '2', 'x': '1', 'z': '3'}

Related: How does zip(*[iter(s)]*n) work in Python?

查看更多
家丑人穷心不美
4楼-- · 2020-04-27 00:41
>>> m = [ (i[0], i[2]) for i in s.split("\n") ]
>>> m
[('x', '1'), ('y', '2'), ('z', '3')]
>>> d = dict(m)
>>> d
{'y': '2', 'x': '1', 'z': '3'}
查看更多
登录 后发表回答