Convert namedtuple to dictionary
Tim Chase
python.list at tim.thechases.com
Wed Sep 25 19:41:25 EDT 2013
On 2013-09-25 15:45, tripsvt at 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
More information about the Python-list
mailing list