Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #54768
| Date | 2013-09-25 20:15 -0400 |
|---|---|
| From | Ned Batchelder <ned@nedbatchelder.com> |
| Subject | Re: Convert namedtuple to dictionary |
| References | <635a3b46-3150-409f-8a9d-002af18fb734@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.328.1380154894.18130.python-list@python.org> (permalink) |
On 9/25/13 6:45 PM, tripsvt@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]}
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Convert namedtuple to dictionary tripsvt@gmail.com - 2013-09-25 15:45 -0700
Re: Convert namedtuple to dictionary Tim Chase <python.list@tim.thechases.com> - 2013-09-25 18:41 -0500
Re: Convert namedtuple to dictionary Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-09-26 01:08 +0000
Re: Convert namedtuple to dictionary MRAB <python@mrabarnett.plus.com> - 2013-09-26 02:15 +0100
Re: Convert namedtuple to dictionary Terry Reedy <tjreedy@udel.edu> - 2013-09-25 21:45 -0400
Re: Convert namedtuple to dictionary Tim Chase <python.list@tim.thechases.com> - 2013-09-26 06:51 -0500
Re: Convert namedtuple to dictionary MRAB <python@mrabarnett.plus.com> - 2013-09-26 00:52 +0100
Re: Convert namedtuple to dictionary Ned Batchelder <ned@nedbatchelder.com> - 2013-09-25 20:15 -0400
Re: Convert namedtuple to dictionary Steven D'Aprano <steve@pearwood.info> - 2013-09-26 03:48 +0000
Re: Convert namedtuple to dictionary Peter Otten <__peter__@web.de> - 2013-09-26 08:47 +0200
csiph-web