Converting tuples to namedtuple methods in python

  • 2021-08-17 00:38:14
  • OfStack

We can think of every one horizontal data in the table as a different tuple. After understanding this concept, we learned a lot about namedtuple class yesterday. Can we also convert tuples into namedtuple? Of course, this is an attempt, which is rarely used by many small partners, and it is difficult to find data collection. This site has also been collected for a long time before it has been harvested. This article will bring you the method of converting tuples into namedtuple in python.

Now that we've seen why we use namedtuple, it's time to learn how to convert regular tuples and into namedtuple. Suppose that for some reason, there are instances containing color RGBA values. If you want to convert it to Color namedtuple, you can do the following:


>>> c = {"r": 50, "g": 205, "b": 50, "alpha": alpha}
>>> Color(**c)
>>> Color(r=50, g=205, b=50, alpha=0)

We can use this * * structure to decompress packets from dict to namedtuple.

A tuple, like a list, is an ordered collection of objects based on position, but the tuple 1 cannot be changed once it is created, so any modification of elements in the list does not apply to the tuple.

Use () to create tuples, and use English commas to separate elements.


num_tuple = (1, 2, 3)
string_tuple = ("a", )

If I want to create an namedtupe from dict, what should I do?


>>> c = {"r": 50, "g": 205, "b": 50, "alpha": alpha}
>>> Color = namedtuple("Color", c)
>>> Color(**c)
Color(r=50, g=205, b=50, alpha=0)

By passing the dict instance to the namedtuple factory function, it will create the field for you. Then, Color extracts the dictionary c like Example 1 above to create a new instance.

After running the code, you can convert the tuple to namedtuple.

Tuple to namedtuple instance extension:

I use namedtuples internally, but I want to maintain compatibility with users who provide ordinary tuples.


from collections import namedtuple
tuplePi=(1,3.14,"pi") #Normal tuple 
Record=namedtuple("MyNamedTuple", ["ID", "Value", "Name"])
namedE=Record(2, 2.79, "e") #Named tuple
namedPi=Record(tuplePi) #Error
TypeError: __new__() missing 2 required positional arguments: 'Value' and 'Name'
tuplePi.__class__=Record
TypeError: __class__ assignment: only for heap types

Related articles: