The standard library namedtuple class looks to me like a way to make tuples more like dictionaries. How do namedtuples compare to dicts? When should we use them? Do they work with non-hashable types?
The standard library namedtuple class looks to me like a way to make tuples
Share
In
dicts, only the keys have to be hashable, not the values.namedtuples don’t have keys, so hashability isn’t an issue.However, they have a more stringent restriction — their key-equivalents, “field names”, have to be strings.
Basically, if you were going to create a bunch of instances of a class like:
and not change the attributes after you set them in
__init__, you could instead useas a replacement.
Of course, you could create a bunch of
dicts where you used the same keys in each one, but assuming you will have only valid Python identifiers as keys and don’t need mutability,is prettier than
and
is prettier than
Finally,
namedtuples are ordered, unlike regulardicts, so you get the items in the order you defined the fields, unlike adict.