Convert namedtuple to dictionary
MRAB
python at mrabarnett.plus.com
Wed Sep 25 19:52:32 EDT 2013
On 25/09/2013 23:45, 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 assume you mean:
{'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}}
>
You can get the field names using ._fields and the values by using
list(...):
>>> n = brucelee(x=123, y=321)
>>> n._fields
('x', 'y')
>>> list(n)
[123, 321]
Zip then together and pass the result to dict:
>>> dict(zip(n._fields, list(n)))
{'x': 123, 'y': 321}
And, finally, putting that in a dict comprehension:
>>> n = {'a': brucelee(x=123, y=321), 'b': brucelee(x=123, y=321)}
>>> {k: dict(zip(v._fields, list(v))) for k, v in n.items()}
{'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]}
>
That's not valid Python!
More information about the Python-list
mailing list