Understanding how to use data types like the python namedtuple vs dict will only help you get better at writing your python code. Python is one of the world’s most important programming languages today and in the world of data science, Python can easily be a programming language that you can use to understand how to work around complex problems and make your analyses simpler. The best part about Python is the flexibility it offers with data types. The data can be mended to fit into the exact data type as required and it will make your analysis simpler.
Also, read -> what is a decorator in python and how to use it? [Explained]
What is a Data type in Python?
A data type is essentially the classification of or the categorization of a certain element of data. The representation in different types is useful in order to understand what type of operations can be conducted on specific types of data. Since Python is an object-oriented programming language, everything in Python is an object and Python is essentially a culmination of different data types that are shown as classes and variables in different instances of Python.
Read more about what a data type is in Python: Python Data Types
Find more about Python as an Object-Oriented Programing Language here: Object-Oriented Programming
Check out this YouTube video if you are still curious about data types in Python:
Different types of data in Python
The standard data types in Python are: (Namedtuple vs Dict are two of these)
- Numeric
- String
- List
- Tuple
- Set
- Dictionary
These are further divided into the following types;
- integer
- float
- complex
- list
- tuple
- range
- string
- set
- frozenset
- boolean
- bytes
- namedtuple
- NoneType
Read more about the different types of data in python here: Official Python documentation for data types
What is a Namedtuple in python?
Of the namedtuple vs dict, the named tuple is an easily created lightweight object or instance in python which can be referenced to using an object-like variable or the standard tuple syntax. The syntax is similar to the dictionary except that they are immutable or in simpler terms, the values in the tuple cannot be rewritten or changed once put into place.
For example:
You can form a named tuple for an x,y point as follows;
from collections import namedtuple Point = namedtuple('Point', 'x y') pt1 = Point(1.0, 5.0) pt2 = Point(2.5, 1.5)
The syntax generally can be used and one should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable.
What is a Dict in Python?
The second of Namedtuple vs dict, a dictionary is a collection of different elements, that are ordered, changeable or mutable and it does not allow duplicates. The dictionaries are denoted by using a curly brace or curly bracket and it has multiple key-value pairs. Of the namedtuple vs dict, the dictionary is very similar to a tuple. The dictionary is a combination of key-value pairs and can have named tuples as a part of the key-value pairs too.
dict = { "brand": "ABC", "model": "XYZ", "time": 1800 } print(dict)
Python Namedtuple vs Dict – Difference explained
Let us go over the differences between Python namedtuple vs dict to know when to use which of them in our code to make the code more readable and easy to execute.
Python Namedtuple vs Dict:
- Python namedtuples are immutable while a dictionary is mutable in python.
- A namedtuple can be used to access elements in the tuple using the names and not just the indexes while the data in a python dict can be accessed using a key:value pairing.
- The namedtuple can be a part of the python dict and can be used to call different key value pairs
- you can add any key value pair or remove it once the creation of dictionary is done while in case of namedtuple we can not do that i.e. you cannot add any elements or change them after the named tuple is created.
You can see it after you execute this code:
from collections import namedtuple Point = namedtuple('Point', ['x','y']) a = Point(1,1) a.x = 3 AttributeError: can't set attribute
You can also try to execute this code to understand namedtuple vs dict in a better way:
import collections # Declaring namedtuple() Student = collections.namedtuple('Student',['name','age','DOJ']) # Adding values S = Student('Abc','10','25022007') # Access using index print ("The Student age using index is : ",end ="") print (S[1]) # Access using name print ("The Student name using keyname is : ",end ="") print (S.name) # Access using getattr() print ("The Student DOB using getattr() is : ",end ="") print (getattr(S,'DOB')) # Initializing dictionary Student ={'Student': 'ABC' , 'age': '10','DOB':'25022007'} # using get() to print a key value print ("The age is : ") print (Student.get('age', "Not Present"))
Conclusion:
The difference between the namedtuple vs dict might not seem like a big deal to most people but understanding the basics is of prime importance when it comes to using a programming language like Python in Data Science. Using a programming language, one can definitely take their analyses to the best possible stages, and knowing the right data types to assign to make sure that the right operations are conducted on data is equally important.
Namedtuples and dictionaries make up data in most cases where a lot of different pre-set values are to be assigned to variables, this can be pay scales or even grades in an exam. Using namedtuples instead of tuples will make your code more readable and reproducible and using the dictionary will make the assignment of values simpler using the key-value pairs.
Try using a namedtuple or dictionary in your workflow with your data or in your coding projects and tell us if they helped your analyses!
For more such content, check out our website -> Buggy Programmer
An eternal learner, I believe Data is the panacea to the world's problems. I enjoy Data Science and all things related to data. Let's unravel this mystery about what Data Science really is, together. With over 33 certifications, I enjoy writing about Data Science to make it simpler for everyone to understand. Happy reading and do connect with me on my LinkedIn to know more!