Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created December 6, 2010 16:33
Show Gist options
  • Save pyrtsa/730533 to your computer and use it in GitHub Desktop.
Save pyrtsa/730533 to your computer and use it in GitHub Desktop.
def dicttuple(typename, field_names, **kwargs)
def dicttuple(typename, field_names, **kwargs):
"Create a namedtuple that can be used like a dict in **keyword expansion."
from itertools import count, izip
from collections import namedtuple
t = namedtuple(typename, field_names, **kwargs)
t._index = dict(izip(t._fields, count()))
t.keys = lambda self: self._fields
t.keys.__doc__ = "List of tuple element names."
f = t.__getitem__
t.__getitem__ = lambda sf,i: sf[sf._index[i]] if isstring(i) else f(sf, i)
t.__getitem__.__doc__ = \
"x[i] Get tuple element named i if i is string, else get i'th element."
return t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment