Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #54762

Re: Convert namedtuple to dictionary

Date 2013-09-25 18:41 -0500
From Tim Chase <python.list@tim.thechases.com>
Subject Re: Convert namedtuple to dictionary
References <635a3b46-3150-409f-8a9d-002af18fb734@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.325.1380152379.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 2013-09-25 15:45, tripsvt@gmail.com wrote:
> 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}}

While it uses the "private" member-variable "_fields", you can do

>>> brucelee = namedtuple("brucelee", "x y")
>>> d = {'a': brucelee(x=123,y=321), 'b': brucelee(x=234,y=432)}
>>> dict((k, dict((s, getattr(v, s)) for s in v._fields)) for k,v in
>>> d.iteritems())
{'a': {'y': 321, 'x': 123}, 'b': {'y': 432, 'x': 234}}

which can be made a bit more readable with a helper function:

>>> def dictify(some_named_tuple):
...     return dict((s, getattr(some_named_tuple, s)) for s in some_named_tuple._fields)
... 
>>> dict((k, dictify(v)) for k,v in d.iteritems())
{'a': {'y': 321, 'x': 123}, 'b': {'y': 432, 'x': 234}}

This would also make it easier to change/choose in the event
"_fields" ever changes.

-tkc



Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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