Python Tuple and Dictionary

Deepa Mariam George
Analytics Vidhya
Published in
4 min readJun 13, 2020

In this section, let’s learn about Python tuples and dictionaries.

Python Tuple

A tuple is a collection which is ordered and unchangeable.

Tuples are identical to lists in all respects, except for the following properties:

  • Tuples are defined by enclosing the elements in parentheses ( ) instead of square brackets [ ] .
  • Tuples are immutable ( elements of a tuple cannot be changed once they have been assigned ).

Creating a Tuple

A tuple is created by placing all the elements inside parentheses( ), separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

Examples:

my_tuple = ();   //Empty tuplemy_tuple = (‘hello’,)
//For creating tuples with a single element, add a trailing comma to indicate that it is a tuple.
my_tuple = (10, ‘cat’, 99.9, (11, 22, 33))
//Nested tuple with mixed data type

Various operations that you have learned and performed on lists such as accessing elements, indexing and negative indexing, slicing, looping through elements, tuple length, checking if an element exists, and sorting are true for tuples as well.

But tuples can’t be modified. The operations such as appending, extending, changing elements, and removing elements from a tuple are not possible, and eventually result in errors.

Deleting a tuple

A tuple can be deleted completely using the del keyword. For example,

my_tuple = (‘cat’, ‘rat’, ‘fish’)
del my_tuple //my_tuple gets deleted completely.

Tuple Methods

Python has two built-in methods count() and index() that you can use on tuples.

count() Method

The count() method returns the number of times a specified value appears in the tuple.

my_tuple = (30, 55, 23, 99, 21, 55, 23, 55, 42, 61, 99, 21, 55)
x = my_tuple.count(55)
//Returns the number of times the value 55 appears in the tuple.
print(x)

The output gives:

4

index() Method

The index() method finds the first occurrence of the specified value. It raises an exception if the value is not found. Here is the example,

my_tuple = (30, 55, 23, 99, 21, 55, 23, 55, 42, 61, 99, 21, 55)
x = my_tuple.index(23)
//Searches for the first occurrence of the value 23, and returns its position.
print(x)

The output will be:

2

Thus, you can use a tuple when you don’t want your data to be modified. If the values in the collection are meant to remain constant for the entire life of the program, using a tuple guards against accidental modification.

Python Dictionaries

Python dictionary is a collection which is unordered, changeable and indexed. Each item of a dictionary has a key:value pair and are written within curly brackets separated by commas. The values can repeat, but the keys must be unique and must be of immutable type(string, number or tuple).

Let’s go through some examples:

my_dict = {} //empty dictionarymy_dict = {1: ‘pizza’, 2: ‘burger’, 3: ‘milk’} 
//dictionary with integer keys
my_dict = {‘name’: ‘Katie’, 1: [10, 20, 30], ‘dateofbirth’:1994 }
//dictionary with mixed keys

Accessing elements from a dictionary

You can access the elements of a dictionary by referring to its key name, inside square brackets.

my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
print(my_dict[‘age’])

There is also a method called get() to access the elements.

my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
print(my_dict.get(‘age’))

Both the above programs give the following result:

20

Changing the value of an element

You can change the value of a specific element by referring to its key name.

my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
my_dict[‘place’] = ‘Australia’

The dictionary ‘my_dict’ becomes:

{‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Australia’}

Looping through a dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return values are the keys of the dictionary.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x in my_dict:
print(x) //print all keys in the dictionary one by one

Output:

name
place
age

Note: Dictionaries are unordered collections. That is, the elements of a dictionary are not stored in any particular order. So, the elements are not iterated over in the same order in which they were created.

To print all the values in the dictionary one by one:

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x in my_dict:
print(my_list[x])

Output:

Mariam
London
20

You can use the items() method for looping through both keys and values.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x, y in my_dict.items():
print(x, “:”, y)

Output:

place : London
name : Mariam
age : 20

Checking if a key exists

To check if a specified key is present in a dictionary use the ‘in’ keyword.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
if ‘name’ in my_dict:
print(“Yes, name is one of the keys in my dictionary.”)

This will give:

Yes, name is one of the keys in my dictionary.

Dictionary Length

To determine how many elements (key-value pairs) a dictionary has, use the len() function.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
print(len(my_dict))

which gives the output:

3

Adding elements to a dictionary

Adding an element to the dictionary is done by using a new index key and assigning a value to it.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict[‘phone’] = 688143
print(my_dict)

The output becomes:

{‘age’: 20, ‘name’: ‘Mariam’, ‘phone’: 688143, ‘place’: ‘London’}

Removing elements from a dictionary

There are various ways to remove elements from a dictionary:

(i) pop() — removes the element with the specified key name.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict.pop(‘age’) //Removes the element with the key ‘age’
print(my_dict)

Output:

{‘name’: ‘Mariam’, ‘place’: ‘London’}

(ii) del — removes the element with the specified key name.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
del my_dict[‘age’]
print(my_dict)

Output:

{‘name’: ‘Mariam’, ‘place’: ‘London’}

The del keyword can also delete the dictionary completely.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
del my_dict //my_dict gets deleted completely.

(iv) clear() — empties the dictionary.

my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict.clear()
print(my_dict)

This will produce an empty dictionary:

{}

--

--