Convert namedtuple to dictionary
Steven D'Aprano
steve at pearwood.info
Wed Sep 25 23:48:05 EDT 2013
On Wed, 25 Sep 2013 15:45:49 -0700, tripsvt wrote:
> Need suggestions.
>
> Say, I have a namedtuple like this:
>
> {'a': brucelee(x=123, y=321), 'b': brucelee('x'=123, 'y'=321)
That's not a namedtuple, that's a dict containing two namedtuples.
> I need to convert it to:
>
> {'a': {'x':123, 'y': 321},'b': {'x':123, 'y': 321}}
Why bother? But if you must:
for key, value in some_dict.items():
some_dict[key] = value._asdict()
ought to work.
> 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 legal Python.
The answer depends on what you mean by "extract/manipulate" the x and y
fields. If all you are doing is looking them up, then a namedtuple is
easiest, since that's what you've already got:
for value in some_dict.values():
print(value.x)
print(value.y)
But if you need to change those values, then a namedtuple is no good
because it is immutable. In that case, you can either create a new
namedtuple, or just use the dict-of-dicts version.
# Untested
for key, value in some_dict.items():
kind = type(value) # what sort of namedtuple is it?
new = kind(value.x+1, value.y+2)
some_dict[key] = new
--
Steven
More information about the Python-list
mailing list