Python Forum

Full Version: how to get the keys in a named tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i know how to get the keys from s dictionary. but how to do that for a named tuple?
look at namedtuple._fields property`

from collections import namedtuple

Spam = namedtuple('Spam', 'foo, bar')

eggs = Spam(1, 2)
print(eggs._fields)
print(Spam._fields)
Output:
('foo', 'bar') ('foo', 'bar')
Also, FYI, you can get namedtuple as dict with _asdict() method
print(eggs._asdict())
Output:
OrderedDict([('foo', 1), ('bar', 2)])
The above and other useful things can be found in the documentation. I'd really recommend familiarising yourself with the library reference ("keep this under your pillow", as the Python docs page says).
i do not keep it under my pillow. it keep it out where i can read it. and i do. it's just not indexed in a lookup manner by concept. it's more of a sequential definition. i still look for things but i don't spend an unlimited time doing that. at some point in time, when i have not found something, i have to move on, or use an associative memory ... asking others who may already know.
(Mar-24-2020, 05:29 PM)Skaperen Wrote: [ -> ]it's just not indexed in a lookup manner by concept.

C'mon, really in this case you are not right. You ask about namedtuple. First thing you can do is check the docs and it's clear where you should look. It's not that long read. If you just have made the effort...
I've answered, no problem, but one should try....
Maybe you are confusing the Language reference and the Library refernce

and of course there is the official Python tutorial and the Python HOWTOs
i looked for it in the Library Reference where i do find lots of stuff but miss many things. i think it might be a failure to recognize with fast reading. i probably need to slowdown.