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


Groups > comp.lang.python > #54783

Re: Convert namedtuple to dictionary

From Peter Otten <__peter__@web.de>
Subject Re: Convert namedtuple to dictionary
Date 2013-09-26 08:47 +0200
Organization None
References <635a3b46-3150-409f-8a9d-002af18fb734@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.337.1380178007.18130.python-list@python.org> (permalink)

Show all headers | View raw


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}}
> 
> 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]}

One more:

>>> from collections import namedtuple
>>> brucelee = namedtuple("brucelee", "x y")
>>> def to_dict(n):
...     return dict(zip(n._fields, n))
... 
>>> data = {'a': brucelee(x=123, y=321), 'b': brucelee(x=123, y=321)}
>>> {k: to_dict(v) for k, v in data.items()}
{'a': {'y': 321, 'x': 123}, 'b': {'y': 321, 'x': 123}}

Back to comp.lang.python | Previous | NextPrevious 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