The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:n:namedtuples

named tuples

named tuples is part of the collections module and must be imported before they can be used.

Named tuple is a data structure like a tuple, but each element has a name like the instance attributes of a class.

Documentation:

# example code:

from collections import namedtuple

Color = namedtuple("Color", "r g b alpha") # note that Color and "Color" must be identical. 

# usage examples
red = Color(r=250, g=0, b=0, alpha=alpha)
print(red.alpha)
blue = Color(r=50, g=0, b=255, alpha=alpha)

use double star method to unpack dict into named tuple

>>> c = {"r": 50, "g": 205, "b": 50, "alpha": alpha}
>>> Color = namedtuple("Color", c) # c is the field list for the named tuple here
>>> Color(**c)
Color(r=50, g=205, b=50, alpha=0)

convert named tuple into dict

>>> blue = Color(r=0, g=0, b=255, alpha=1.0)
>>> blue._asdict()
{'r': 0, 'g': 0, 'b': 255, 'alpha': 1.0}

sort a list of named tuples by a specific key

from collections import namedtuple
from operator import attrgetter
 
# define named Tuple
Color = namedtuple("Color", "r g b alpha") 
 
# unsorted list of named tuple
mycolors = [
    Color(r=50, g=205, b=50, alpha=0.1),
    Color(r=50, g=205, b=50, alpha=0.5),
    Color(r=50, g=0, b=0, alpha=0.3)
]
 
sorted(mycolors, key=attrgetter("alpha"))
# pretty output, sorted by alpha value
for c in mycolors:
    print(c)

# output should be:
#Color(r=50, g=205, b=50, alpha=0.1)
#Color(r=50, g=205, b=50, alpha=0.5)
#Color(r=50, g=0, b=0, alpha=0.3)

en/glossary/n/namedtuples.txt · Last modified: 2020/12/29 06:59 by horst