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 hidden or 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_fmtmodule, theserializefunction accepts a dictionary (e.g. from ajson.loadcall) and will convert to an instance of the givennamedtuple-deriving type. Likewise,deserializewill convert anynamedtuple-deriving type into a dictionary-l object. These functions also work on anylist-like type:ListandTupleare process-able.E.g.
Implementation note: There are explicit type checks for the
Sequencetypes. It's important to not mess-up when it comes to handlingstrandtuple. A first draft of this idea incorrectly didfor _ in Xwhen trying to "test" if something waslist-like. This idea, unfortunately, will iterate over characters in astror elements in atuple. We want thetuple-iterating part, but not when it comes to aNamedTuple(ornamedtuple)![1] https://gist.github.com/malcolmgreaves/d71ae1f09075812e54d8ec54a5613616