When and why should I use a namedtuple instead of a dictionary?

Python

Python Problem Overview


> Possible Duplicate:
> What are “named tuples” in Python?

What is the situation where a namedtuple should be used?

When I looked into it, it looked like a way to make tuples more like dictionaries. How do they compare to dictionaries?

Can only the same hashable types for dictionaries be used for namedtuples?

Python Solutions


Solution 1 - Python

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:

class Container:
    def __init__(self, name, date, foo, bar):
        self.name = name
        self.date = date
        self.foo = foo
        self.bar = bar

mycontainer = Container(name, date, foo, bar)

and not change the attributes after you set them in __init__, you could instead use

Container = namedtuple('Container', ['name', 'date', 'foo', 'bar'])

mycontainer = Container(name, date, foo, bar)

as 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,

mynamedtuple.fieldname

is prettier than

mydict['fieldname']

and

mynamedtuple = MyNamedTuple(firstvalue, secondvalue)

is prettier than

mydict = {'fieldname': firstvalue, 'secondfield': secondvalue}

Finally, namedtuples are ordered, unlike regular dicts, so you get the items in the order you defined the fields, unlike a dict.

Solution 2 - Python

Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple, it doesn't perform any hashing — it generates a new type instead.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJack_of_All_TradesView Question on Stackoverflow
Solution 1 - PythonagfView Answer on Stackoverflow
Solution 2 - PythonCat Plus PlusView Answer on Stackoverflow