[Tutor] appending/updating values dict key value pairs

eryksun eryksun at gmail.com
Sun Jun 23 12:37:07 CEST 2013


On Sun, Jun 23, 2013 at 5:42 AM, Sivaram Neelakantan
<nsivaram.net at gmail.com> wrote:
> I've sort of used a dict of this sort {'a': [1,2,'fff'] } in my
> programs and I've noticed that I've got to unpack the list with
> hardcoded list positions when I retrieve the value of a key.
>
> I think I'd be better off, if I did something of
>
> {'a' : ['foo': 1, 'bar':2, 'offset': 'fff'] }
>
> wouldn't that be better from a maintainability POV?  Are there any
> examples of such?  Or is there a 'struct' option for python?  I don't
> want to use OO methods for now.

The correct syntax is a dict of dicts:

    {'a': {'foo': 1, 'bar': 2, 'offset': 'fff'}}

A dict is something of a resource hog, and it's unordered. Use it as
the container because it's mutable and lookups are fast, but for the
values consider using a namedtuple. It has a smaller footprint, and
it's ordered.

    from collections import namedtuple

    Record = namedtuple('Record', 'foo bar offset')

You can initialize an instance using either positional or keyword arguments:

    data = {
        'a': Record(1, 2, 0xfff),
        'b': Record(foo=3, bar=4, offset=0xaaa),
    }

Access the fields by index or attribute:

    >>> a = data['a']; a[0], a[1], a[2]
    (1, 2, 4095)

    >>> b = data['b']; b.foo, b.bar, b.offset
    (3, 4, 2730)

A tuple is immutable, so modifying a field requires a new tuple. Use
the _replace method:

    >>> data['b'] = data['b']._replace(offset=0xbbb)

    >>> b = data['b']; b.foo, b.bar, b.offset
    (3, 4, 3003)


If you're curious, it's easy to see how namedtuple works:

    >>> Record = namedtuple('Record', 'foo bar offset', verbose=True)
    class Record(tuple):
        'Record(foo, bar, offset)'

        __slots__ = ()

        _fields = ('foo', 'bar', 'offset')

        def __new__(_cls, foo, bar, offset):
            'Create new instance of Record(foo, bar, offset)'
            return _tuple.__new__(_cls, (foo, bar, offset))
    ...


More information about the Tutor mailing list