On 25/09/2013 23:45, trip...@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!
--
https://mail.python.org/mailman/listinfo/python-list