1

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?

alvas
  • 105,505
  • 99
  • 405
  • 683

3 Answers3

4

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'}
>>>
PaulMcG
  • 59,676
  • 15
  • 85
  • 126
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?

Community
  • 1
  • 1
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
0
>>> 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'}
Ankur Agarwal
  • 21,824
  • 36
  • 127
  • 196