Created
December 6, 2010 16:33
-
-
Save pyrtsa/730533 to your computer and use it in GitHub Desktop.
def dicttuple(typename, field_names, **kwargs)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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