accessing dictionary keys

Discussion in 'Python' started by Andreas Balogh, Oct 1, 2009.

  1. 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, Oct 1, 2009
    #1
    1. Advertisements

  2. 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,
     
    Carsten Haese, Oct 1, 2009
    #2
    1. Advertisements

  3. It sounds like you want collections.namedtuple (Python 2.6 and up; recipe
    for Python 2.4 or 2.5 at http://code.activestate.com/recipes/500261/)?

    HTH,
    Rami
     
    Rami Chowdhury, Oct 1, 2009
    #3
  4. Andreas Balogh

    Jerry Hill Guest

    A namedtuple (introduced in python 2.6), acts like a tuple with named
    fields. Here's an example:
    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 Hill, Oct 1, 2009
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.