Questions tagged [namedtuple]

namedtuple is a data structure provided by the Python collections module. It enables the creation of tuples with named elements (e.g., a Student tuple with the values (name, school, age) rather than a tuple with just two strings and an integer).

namedtuple is a data structure provided by the Python collections module. It enables the creation of tuples with named elements (e.g., a Student tuple with the values (name, school, age) rather than a tuple with just two strings and an integer).

Documentation: collections module in Python 3.

Recently, a declarative API for namedtuples is also provided by the typing module.

545 questions
1192
votes
13 answers

What are "named tuples" in Python?

What are named tuples and how do I use them? When should I use named tuples instead of normal tuples, or vice versa? Are there "named lists" too? (i.e. mutable named tuples) For the last question specifically, see also Existence of mutable named…
Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111
393
votes
23 answers

Named tuple and default values for optional keyword arguments

I'm trying to convert a longish hollow "data" class into a named tuple. My class currently looks like this: class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right =…
sasuke
  • 6,589
  • 5
  • 36
  • 35
235
votes
3 answers

Type hints in namedtuple

Consider following piece of code: from collections import namedtuple point = namedtuple("Point", ("x:int", "y:int")) The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints. Do…
232
votes
7 answers

Data Classes vs typing.NamedTuple primary use cases

Long story short PEP-557 introduced data classes into Python standard library, that basically can fill the same role as collections.namedtuple and typing.NamedTuple. And now I'm wondering how to separate the use cases in which namedtuple is still a…
Oleh Rybalchenko
  • 6,998
  • 3
  • 22
  • 36
228
votes
6 answers

Convert a namedtuple into a dictionary

I have a named tuple class in python class Town(collections.namedtuple('Town', [ 'name', 'population', 'coordinates', 'population', 'capital', 'state_bird'])): # ... I'd like to convert Town instances into…
Without Me It Just Aweso
  • 4,593
  • 10
  • 35
  • 53
172
votes
10 answers

How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__?

I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should the class…
MWB
  • 11,740
  • 6
  • 46
  • 91
163
votes
14 answers

Existence of mutable named tuple in Python?

Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects? Primarily for readability, I would like something similar to namedtuple that does this: from Camelot import namedgroup Point = namedgroup('Point',…
Alexander
  • 105,104
  • 32
  • 201
  • 196
108
votes
5 answers

How to access a field of a namedtuple using a variable for the field name?

I can access elements of a named tuple by name as follows(*): from collections import namedtuple Car = namedtuple('Car', 'color mileage') my_car = Car('red', 100) print my_car.color But how can I use a variable to specify the name of the field I…
LangeHaare
  • 2,776
  • 2
  • 17
  • 25
107
votes
10 answers

Pythonic way to convert a dictionary into namedtuple or another hashable dict-like?

I have a dictionary like: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} which I would like to convert to a namedtuple. My current approach is with the following code namedTupleConstructor = namedtuple('myNamedTuple', ' '.join(sorted(d.keys()))) nt=…
Max Power
  • 8,265
  • 13
  • 50
  • 91
106
votes
12 answers

Serializing a Python namedtuple to json

What is the recommended way of serializing a namedtuple to json with the field names retained? Serializing a namedtuple to json results in only the values being serialized and the field names being lost in translation. I would like the fields also…
calvinkrishy
  • 3,798
  • 8
  • 30
  • 45
93
votes
10 answers

Adding docstrings to namedtuples?

Is it possible to add a documentation string to a namedtuple in an easy manner? I tried from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) """ A point in 2D space """ # Yet another test """ A(nother) point in 2D…
Rickard
  • 1,754
  • 1
  • 12
  • 17
84
votes
5 answers

Pythonic way to sorting list of namedtuples by field name

I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution. from operator import itemgetter from collections import…
Nick
  • 873
  • 1
  • 6
  • 7
71
votes
5 answers

How to pickle a namedtuple instance correctly

I'm learning how to use pickle. I've created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error: pickle.PicklingError: Can't pickle : it's not found as __main__.P I…
Dirty Penguin
  • 4,212
  • 9
  • 45
  • 69
66
votes
1 answer

What does *tuple and **dict mean in Python?

As mentioned in PythonCookbook, * can be added before a tuple. What does * mean here? Chapter 1.18. Mapping Names to Sequence Elements: from collections import namedtuple Stock = namedtuple('Stock', ['name', 'shares', 'price']) s = Stock(*rec) #…
heLomaN
  • 1,634
  • 2
  • 22
  • 33
62
votes
5 answers

namedtuple._replace() doesn't work as described in the documentation

I was having trouble implementing namedtuple._replace(), so I copied the code right off of the documentation: Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p and I got: Point(x=11, y=22) instead of: Point(x=33,…
Peter Stewart
  • 2,857
  • 6
  • 28
  • 30
1
2 3
36 37