Convert a string with 2-tier delimiters into a dictionary - python

喜你入骨 提交于 2019-12-02 13:31:58

问题


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?


回答1:


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'}
>>>



回答2:


>>> 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?




回答3:


>>> 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'}


来源:https://stackoverflow.com/questions/18687472/convert-a-string-with-2-tier-delimiters-into-a-dictionary-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!