Reputation: 996
I've just learning python after PHP, and it's python style is very strange for me. I'm asking for advice, how you write this code on python:
data = []
for line in file:
name, surname, phone, address, email, etc = line.split(";", 6)
data.append( {'nick': nick, 'surname': surname, 'phone': phone, 'address': address, 'email': email, 'etc': etc} )
My code looks like PHP -_-
Upvotes: 0
Views: 169
Reputation: 88977
You can use a list comprehension here:
[{'nick': nick, 'surname': surname, 'phone': phone, 'address': address, 'email': email, 'etc': etc} for name, surname, phone, address, email, etc in (line.split(";", 6) for line in file)]
However, this is pretty hard to read due to it's length.
To construct your data, you could use collections.namedtuple
or a function that produces a dict (as in ThiefMaster's answer).
An alternate solution here is to create a class to hold your data:
def Person:
def __init__(self, nick, surname, phone, address, email, etc):
self.nick = nick
self.surname = surname
...
And then construct your list using the splat operator to unpack your values:
data = [Person(*line.split(";", 6)) for line in file]
This is suitable where you intend to do more work with the data - the rule of thumb here is that if you don't make any methods to work on the data, a class is more power than you need. If you do, it might be worthwhile.
Upvotes: 0
Reputation: 318468
I would use a function to do the parsing and then use map()
to call it on each line:
def _parse_user_line(line):
name, surname, phone, address, email, etc = line.split(';', 6)
return {'nick': nick, 'surname': surname, 'phone': phone,
'address': address, 'email': email, 'etc': etc}
data = map(_parse_user_line, file)
It might also be a good idea to assign the returned list to a single variable and then just use fields[0]
, fields[1]
etc. - they will be next to the dict key anyway so everyone knows what they are:
def _parse_user_line(line):
u = line.split(';', 6)
return {'nick': u[0], 'surname': u[1], 'phone': u[2],
'address': u[3], 'email': u[4], 'etc': u[5]}
data = map(_parse_user_line, file)
Now we can make this even nicer by incorporating the idea from Roman's answer:
labels = 'nick surname phone address email etc'.split()
def _parse_user_line(line):
values = line.split(';', 6)
return dict(zip(labels, values))
data = map(_parse_user_line, file)
Never forget (a line from) The Zen of Python (aka import this
): Readability counts.
Upvotes: 2
Reputation: 214949
Your code looks like php because you're reinventing the wheel. Don't!
import csv
fieldnames = ['name', 'surname', 'phone', 'address', 'email']
with open('something', 'r') as f:
data = list(csv.DictReader(f, fieldnames, delimiter=';'))
Upvotes: 4
Reputation: 29707
It is ok. Sure, you may do something like:
data.append(dict(zip(('name', 'surname', 'phone', 'address', 'email', 'etc'),
line.split(";", 6))))
but your variant is more readable.
Upvotes: 4