Dictionary and Tuple in Python – Difference in Properties

In this post, we will learn about tuples and dictionaries in python and how to use tuples as dictionary keys.

What is tuple in python?

A tuple is an ordered and immutable collection. Tuples can hold homogeneous values as well as heterogeneous values(integers, floats, strings, lists, dictionaries, etc). Tuples are sequential, thus they can be indexed and sliced.

Tuple Creation, Packing, and Unpacking

Syntactically, a tuple is a comma-separated list of values.

In python, this type of tuple declaration is called packing of a tuple, because it packs all left-hand side values together in a tuple.

Parenthesis() are optional in tuples except for creating empty tuple. However, it is good practice to use parenthesis.

Creating a tuple containing one element is a bit tricky. The single element should have a comma at the end because it is the comma that defines a tuple not parenthesis.

Tuple unpacking allows extracting tuple elements automatically by assigning each value on the right-hand side to its respective variable on the left side. Thus the number of variables on left must match the number of values on right. All the expressions on the right side are evaluated before any of the assignments.

Dictionary in python

Dictionary is an unordered collection of mutable values indexed by unique keys. Dictionaries are just like map(), storing, and retrieving
elements by referencing a key. Thus keys must be of an immutable data type(Strings, Tuples, Integers, etc.) whereas values can be of any type python supports, there are no restrictions on dictionary values. As dictionaries are referenced by key, they have very fast lookups. The syntax of a dictionary is as follows:

Dictionary_name = {key: value}

Dictionaries can be created in many ways:


Dictionary and tuple:

A dictionary key must be of hashable type because a hashable object does not change during its lifetime. Therefore, tuples can be used as dictionary keys as they are unchangeable. However, neither a list nor another dictionary can be used as a dictionary key, because lists and dictionaries are mutable.

Tuples can be used to make a composite key to dictionaries.

Example: Creating  to store marks of students by mapping roll numbers and subjects to marks:

For loop can be used to iterate through this Dictionary.

Tags: creating dictionary, dictionary, Dictionary in python, packing a tuple, packing and unpacking a tuple, Python, single element in tuple, Tuple, tuple and dictionary, tuple in python, tuple is hashable, unpacking a tuple




%d bloggers like this: