accessing dictionary keys
Jerry Hill
malaclypse2 at gmail.com
Thu Oct 1 16:44:57 EDT 2009
On Thu, Oct 1, 2009 at 4:19 PM, Andreas Balogh <baloand at gmail.com> wrote:
> 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.
--
Jerry
More information about the Python-list
mailing list