alvas
alvas

Reputation: 122152

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

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?

Upvotes: 1

Views: 537

Answers (3)

Ankur Agarwal
Ankur Agarwal

Reputation: 24768

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

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251061

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

Upvotes: 2

PaulMcG
PaulMcG

Reputation: 63747

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

Upvotes: 4

Related Questions