Mohd Ali
Mohd Ali

Reputation: 311

What is the Pythonic way of doing this?

I want a list of dicts for some data, I tried doing it this way:

dataList = ['Jim    5656    qwgh', 'Tim    5833    qwgh']

dataDictList = [ {'name': data[0], 'sknum': data[1]} for data.split('\t') in dataList ]

I get syntax error, which I'm guessing is because 'data.split('\t')' is not working somehow.

I can do this in not so Pythonic way like below, but this is something I don't want to do.

dataDictList = []    

for d in dataList:
    data = d.split('\t')
    dataDictList.append({ 'name': data[0], 'sknum': data[1] })

I would like to know the reason why the above part shows a syntax error.

Upvotes: 0

Views: 80

Answers (3)

The6thSense
The6thSense

Reputation: 8335

How about using map and split

code

dataList = ['Jim    5656    qwgh', 'Tim    5833    qwgh']
dataDictList = [ {'name': data[0], 'sknum': data[1]} for data in map(str.split, dataList)]
dataDictList
[{'name': 'Jim', 'sknum': '5656'}, {'name': 'Tim', 'sknum': '5833'}]

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 122026

Should you really want a one-liner:

>>> dataList = ['Jim    5656    qwgh', 'Tim    5833    qwgh']
>>> [dict(zip(['name', 'sknum'], s.split())) for s in dataList]
[{'name': 'Jim', 'sknum': '5656'}, {'name': 'Tim', 'sknum': '5833'}]

Upvotes: 6

Stephane Rolland
Stephane Rolland

Reputation: 39906

what about:

dataList = ['Jim    5656    qwgh', 'Tim    5833    qwgh']
splitDataList = [data.split('\t') for data in dataList ]

dataDictList = [ {'name': data[0], 'sknum': data[1]} for data in splitDataList ]

Upvotes: 0

Related Questions