What is the difference between a python tuple and a dictionary?

PythonProgrammingServer Side Programming

In this article, we will discuss the difference between a python tuple and dictionary.

Tuple

Tuples are a data type that belongs to the sequence data type category. They're similar to lists in Python, but they have the property of being immutable. We can't change the elements of a tuple, but we can execute a variety of actions on them such as count, index, type, etc.

Tuples are created in Python by placing a sequence of values separated by a 'comma', with or without the use of parenthesis for data grouping. Tuples can have any number of elements and any type of data (like strings, integers, lists, etc.).

Example

In the below example we will look at how to create a tuple.

tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills') print(tuple)

Output

The above code produces the following results

('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')

Dictionary

A dictionary is a Python container that maintains mappings of unique keys to values in an unordered and mutable manner. Data values are stored in key:value pairs using dictionaries.

Dictionaries are written with curly brackets and have keys and values.

Dictionaries are now ordered as of Python 3.7. Dictionaries in Python 3.6 and before are not sorted.

Example

Following is an example to create a dictionary −

thisdict = { "companyname": "Tutorialspoint", "tagline" : "simplyeasylearning", } print(thisdict)

Output

The above code produces the following results

{'companyname': 'Tutorialspoint', 'tagline': 'simplyeasylearning'}

Differences between a tuple and a dictionary

The following are the main differences between a tuple and a dictionary in python.

Tuple Dictionary
A tuple is a non-homogeneous data structure that can hold a single row as well as several rows and columns. Dictionary is a non-homogeneous data structure that contains key-value pairs.
Tuples are represented by brackets (). Dictionaries are represented by curly brackets {}.
Tuples are immutable i.e, we can not make changes. Dictionaries are mutable and keys do not allow duplicates.
A tuple is ordered. Dictionary is ordered (python 3.7 and above).
Tuple can be created using tuple() function. Dictionary can be created using the dict() function.
Creating an empty Tuple: () Creating an empty dictionary: {}
As tuples are immutable, the reverse() method is not defined in them. Because the dictionary's entries are in the form of key-value pairs, the elements cannot be reversed.
Example: ('Tutorialspoint', 'simple’, ‘easy learning’) Example : {'companyname': 'Tutorialspoint', 'tagline': 'simplyeasylearning'}
raja
Updated on 05-Sep-2022 09:04:52

Advertisements