Issue
Using python 2.7 (requirement coming from other factors):
Given I have
x1=["John", "Doe"]
x2=["Jane", "Dan"]
x=[x1, x2]
I need to have some function convert
such that y=convert(x)
(or on an individual x#
), and I will be able to access those values by a field-name, i.e.
>>y[1].name
Jane
>>y[0].surname
Doe
I've tried with map
this way:
y=map(lambda person: {"name":person[0], "surname":person[1]}, x)
But it only works doing y[1]["name"]
, but not y[1].name
.
Can I get some assistance? I'm sure I'm 99% done, but I can't find the quid of it.
Solution
y
becomes a list of dicts, not a list of classes.
>>> print(list(y))
[{'name': 'John', 'surname': 'Doe'}, {'name': 'Jane', 'surname': 'Dan'}]
Python is not Javascript; you cannot use dot-notation to access fields of dictionaries.
If this is what you wanted, you could use a NamedTuple, which creates a class with properties.
from collections import namedtuple
x1=["John", "Doe"]
x2=["Jane", "Dan"]
x=[x1, x2]
Person = namedtuple('Person', ['name', 'surname'])
y = map(lambda person: Person(name=person[0], surname=person[1]), x)
for p in y:
print "{} {}".format(p.name, p.surname)
Same answer applies for Python3 when you do (and should) upgrade.
Answered By - OneCricketeer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.