accessing dictionary keys

A

Andreas Balogh

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
 
C

Carsten Haese

Andreas said:
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

I'm not sure exactly what you're asking, but maybe the following code
will serve as a zeroth iteration toward the solution you seek:

py> class Point(object):
.... def __init__(self, x, y):
.... self.x = x
.... self.y = y
....
py> points = []
py> points.append(Point(1, 2))
py> points.append(Point(2, 3))
py>
py> point = points[0]
py> print point.x, point.y
1 2

HTH,
 
J

Jerry Hill

Is there any shortcut which allows to use point.x with a dictionary, or
defining keys with tuples and lists?

A namedtuple (introduced in python 2.6), acts like a tuple with named
fields. Here's an example:
from collections import namedtuple
Point = namedtuple('Point', 'x y')
points = []
points.append(Point(1, 2))
points [Point(x=1, y=2)]
points.append(Point(2, 3))
points [Point(x=1, y=2), Point(x=2, y=3)]
points[0].x 1
points[0].y 2
points[0][0] 1
points[0][1] 2

See http://docs.python.org/library/collections.html#collections.namedtuple
for more information. I believe there is a recipe in the online
python cookbook that provides this same functionality for earlier
versions of python.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top