[Tutor] appending/updating values dict key value pairs
Sivaram Neelakantan
nsivaram.net at gmail.com
Sun Jun 23 15:43:41 CEST 2013
On Sun, Jun 23 2013,eryksun wrote:
[snipped 14 lines]
> 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))
[snipped 6 lines]
Thanks for the explanation, I'd go with namedtuple as recommended.
sivaram
--
More information about the Tutor
mailing list