Convert namedtuple to dictionary
Ned Batchelder
ned at nedbatchelder.com
Wed Sep 25 20:15:45 EDT 2013
On 9/25/13 6:45 PM, tripsvt at gmail.com wrote:
> Need suggestions.
>
> Say, I have a namedtuple like this:
>
> {'a': brucelee(x=123, y=321), 'b': brucelee('x'=123, 'y'=321)
>
> I need to convert it to:
>
> {'a': {'x':123, 'y': 321},'b': {'x':123, 'y': 321}}
Namedtuples have a ._asdict() method. You can convert your dictionary of
namedtuples (let's call it tupledict) like this:
dictdict = { k: nt._asdict() for k, nt in tupledict }
--Ned.
> Follow-up question --
>
> Which would be easier to work with if I had to later extract/manipulate the 'x', 'y' values? The format (dicts) above or a list of values like this:
>
> {'a': ['x':123, 'y': 321],'b': ['x':123, 'y': 321]}
More information about the Python-list
mailing list