Here is a demonstration of the usage:
>>> fields = ['name', 'population', 'coordinates', 'capital', 'state_bird'] >>>
Town = collections.namedtuple('Town', fields) >>>
funkytown = Town('funky', 300, 'somewhere', 'lipps', 'chicken') >>>
funkytown._asdict()
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')
])
Note: For some 2.7.5 < python version < 3.5.0 code out in the wild, you might see this version:
>>> vars(funkytown)
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')
])
Normally _asdict()
returns a OrderedDict
. this is how to convert from OrderedDict
to a regular dict
town = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
dict(town._asdict())
the output will be
{
'capital': 'lipps',
'coordinates': 'somewhere',
'name': 'funky',
'population': 300,
'state_bird': 'chicken'
}
$ python2.7
# Works on:
# Python 2.7 .6(
default, Jun 22 2015, 17: 58: 13)[GCC 4.8 .2] on linux2
# Python 3.4 .3(
default, Oct 14 2015, 20: 28: 29)[GCC 4.8 .4] on linux
import collections
Color = collections.namedtuple('Color', ['r', 'g', 'b'])
red = Color(r = 256, g = 0, b = 0)
# Access the namedtuple as a dict
print(red.__dict__['r']) # 256
# Drop the namedtuple only keeping the dict
red = red.__dict__
print(red['r']) #256
It would be nice to accumulate a table of major python versions and platforms and their support for __dict__
, currently I only have one platform version and two python versions as posted above.
| Platform | PyVer | __dict__ | _asdict | | -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- -- -- - | -- -- -- -- | -- -- -- - | | Ubuntu 14.04 LTS | Python2 .7 | yes | yes | | Ubuntu 14.04 LTS | Python3 .4 | yes | yes | | CentOS Linux release 7.4 .1708 | Python2 .7 | no | yes | | CentOS Linux release 7.4 .1708 | Python3 .4 | no | yes | | CentOS Linux release 7.4 .1708 | Python3 .6 | no | yes |
Case #1: one dimension tuple
TUPLE_ROLES = ( (912, "Role 21"), (913, "Role 22"), (925, "Role 23"), (918, "Role 24"), ) TUPLE_ROLES[912] # == > Error because it is out of bounce. TUPLE_ROLES[2] # == > will show Role 23. DICT1_ROLE = { k: v for k, v in TUPLE_ROLES } DICT1_ROLE[925] # will display "Role 23"
Case #2: Two dimension tuple
Example: DICT_ROLES[961] # will show 'Back-End Programmer'
NAMEDTUPLE_ROLES = ( ('Company', ( (111, 'Owner/CEO/President'), (113, 'Manager'), (115, 'Receptionist'), (117, 'Marketer'), (119, 'Sales Person'), (121, 'Accountant'), (123, 'Director'), (125, 'Vice President'), (127, 'HR Specialist'), (141, 'System Operator'), )), ('Restaurant', ( (211, 'Chef'), (212, 'Waiter/Waitress'), )), ('Oil Collector', ( (211, 'Truck Driver'), (213, 'Tank Installer'), (217, 'Welder'), (218, 'In-house Handler'), (219, 'Dispatcher'), )), ('Information Technology', ( (912, 'Server Administrator'), (914, 'Graphic Designer'), (916, 'Project Manager'), (918, 'Consultant'), (921, 'Business Logic Analyzer'), (923, 'Data Model Designer'), (951, 'Programmer'), (953, 'WEB Front-End Programmer'), (955, 'Android Programmer'), (957, 'iOS Programmer'), (961, 'Back-End Programmer'), (962, 'Fullstack Programmer'), (971, 'System Architect'), )), ) #Thus, we need dictionary / set T4 = {} def main(): for k, v in NAMEDTUPLE_ROLES: for k1, v1 in v: T4.update({ k1: v1 }) print(T4[961]) # will display 'Back-End Programmer' # print(T4) # will display all list of dictionary main()
if no _asdict(), you can use this way:
def to_dict(model):
new_dict = {}
keys = model._fields
index = 0
for key in keys:
new_dict[key] = model[index]
index += 1
return new_dict
Python 3. Allocate any field to the dictionary as the required index for the dictionary, I used 'name'.
import collections
Town = collections.namedtuple("Town", "name population coordinates capital state_bird")
town_list = []
town_list.append(Town('Town 1', '10', '10.10', 'Capital 1', 'Turkey'))
town_list.append(Town('Town 2', '11', '11.11', 'Capital 2', 'Duck'))
town_dictionary = {
t.name: t
for t in town_list
}
Last Updated : 14 Mar, 2022
Syntax:
for i in list:
print(dict(i._asdict()))
Now that we understand the motivations behind using namedtuple, it’s time to learn how to convert normal tuples and dictionaries into named tuples. ,We've just learned how to convert a namedtuple from a dict. What about the inverse? How can we convert a namedtuple to a dictionary instance?,We'll see the most important aspects of a named tuple in Python 3 and, starting from the very basics, we'll move up to more complex concepts. You’ll learn why you should use them and how you can use them to create cleaner, pythonic code.,On the other hand, namedtuples are just an extension a regular tuple. That means their implementation is based on a faster C code and have a smaller memory footprint.
Suppose that you have a function that converts a string into a color. The color must be represented in a 4-dimensional space, the RGBA.
def convert_string_to_color(desc: str, alpha: float = 0.0):
if desc == "green":
return 50, 205, 50, alpha
elif desc == "blue":
return 0, 0, 255, alpha
else:
return 0, 0, 0, alpha
Then, we can use it like this:
r, g, b, a = convert_string_to_color(desc = "blue", alpha = 1.0)
Ok, that works, but... we have a couple of problems here. The first one is, there's no way to ensure the order of the returned values. That is, there's nothing stopping another developer to call convert_string_to_color
like this:
g, b, r, a = convert_string_to_color(desc = "blue", alpha = 1.0)
Python’s dictionaries are a very versatile data structure. They can serve as an easy and convenient way to store multiple values. However, a dict
doesn’t come without shortcomings. Due to its flexibility, dictionaries are very easily abused. As an illustration, let us convert our example to use a dictionary instead of tuple.
def convert_string_to_color(desc: str, alpha: float = 0.0):
if desc == "green":
return {
"r": 50,
"g": 205,
"b": 50,
"alpha": alpha
}
elif desc == "blue":
return {
"r": 0,
"g": 0,
"b": 255,
"alpha": alpha
}
else:
return {
"r": 0,
"g": 0,
"b": 0,
"alpha": alpha
}
Ok, we now can use it like this, expecting just one value to be returned:
color = convert_string_to_color(desc = "blue", alpha = 1.0)
As an OrderedDict datatype item, NamedTuple can yield items with its keys. We can call the _asdict() function to convert it to an OrderedDict.,We can also convert a dictionary data type object to a NamedTuple collection. The ** operative is required for this transformation.,Different collections can be converted to NamedTuple using a few techniques. We can also use the _make() function to transform a list, tuple, or other iterable objects into a NamedTuple instance.,A NamedTuple in Python cannot be modified, much like its ordinary version. We are unable to alter its characteristics.
32
15
11
"English"
79
"Itika"
The name and country of the first participant are: Itika and India The name and country of the second participant are: Arshia and Australia The Age of participant 1 and 2 are: 21 and 19
Participant(Name = 'Itika', Age = '21', Country = 'India')
Participant(Name = 'Arshia', Age = '19', Country = 'Australia') {
'Name': 'Itika',
'Age': '21',
'Country': 'India'
}
Participant(Name = 'Itika', Age = '21', Country = 'India')
The fields of Participant: ('Name', 'Age', 'Country')
Participant(Name = 'Itika', Age = '21', Country = 'Germany')
AttributeError Traceback(most recent call last)
Input In[41], in()
2 Student = namedtuple("Student", ["Name", "Class", "Age", "Subject", "Marks"])
3 Student1 = Student("Arshia", 12, 17, "Maths", 93)
-- -- > 4 Student1.Class = 11
AttributeError: can 't set attribute