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?
You're a little verbose in your walking through list comprehensions:
str.split()
takes care of all type of white-space characters. If the delimiters were*
and$
for example, then you could usere.split
:Related: How does
zip(*[iter(s)]*n)
work in Python?