Created
October 27, 2011 12:00
-
-
Save href/1319371 to your computer and use it in GitHub Desktop.
Convert any dictionary to a named tuple
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
from collections import namedtuple | |
def convert(dictionary): | |
return namedtuple('GenericDict', dictionary.keys())(**dictionary) | |
""" | |
>>> d = dictionary(a=1, b='b', c=[3]) | |
>>> named = convert(d) | |
>>> named.a == d.a | |
True | |
>>> named.b == d.b | |
True | |
>>> named.c == d.c | |
True | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote up this [1] implementation a little while ago. Stumbled upon this thread. From the
namedtuple_fmt
module, theserialize
function accepts a dictionary (e.g. from ajson.load
call) and will convert to an instance of the givennamedtuple
-deriving type. Likewise,deserialize
will convert anynamedtuple
-deriving type into a dictionary-l object. These functions also work on anylist
-like type:List
andTuple
are process-able.E.g.
Implementation note: There are explicit type checks for the
Sequence
types. It's important to not mess-up when it comes to handlingstr
andtuple
. A first draft of this idea incorrectly didfor _ in X
when trying to "test" if something waslist
-like. This idea, unfortunately, will iterate over characters in astr
or elements in atuple
. We want thetuple
-iterating part, but not when it comes to aNamedTuple
(ornamedtuple
)![1] https://gist.github.com/malcolmgreaves/d71ae1f09075812e54d8ec54a5613616