accessing dictionary keys
Andreas Balogh
baloand at gmail.com
Thu Oct 1 16:19:18 EDT 2009
Hello,
when building a list of points like
points = [ ]
points.append((1, 2))
points.append((2, 3))
point = points[0]
eventually I'd like to access the tuple contents in a more descriptive
way, for example:
print point.x, point.y
but instead I have to write (not very legible)
print point[0], point[1]
Note: I am using Python 2.5
Well, I can use a dictionary:
points.append({"x": 1, "y": 2})
When accessing values more typing is involved:
print point["x"], point["y"]
Or I can use a Bunch (see ActiveState cookbooks):
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
and do it like this:
points.append(Bunch(x=4, y=5))
print points[-1].x, points[-1].y
With the bunch at least all the quotes go away.
Is there any shortcut which allows to use point.x with a dictionary, or
defining keys with tuples and lists?
Regards, Andreas
--
Andreas Balogh
baloand (at) gmail.com
More information about the Python-list
mailing list