HomeComputer ScienceClass 11Tuple And Dictionary in Python

Chapter 8: Tuple and Dictionary

Introduction to Tuples

Tuple is a data structure in Python with the following characteristics:

  • Tuple is immutable (cannot be changed after creation)
  • Enclosed within parentheses ()
  • It's like a list but immutable
  • They can be heterogeneous (elements need not be of same data type)
  • Permit duplicate values

Note: Tuples are immutable, but member objects may be mutable.

Syntax

<Tuple_name/variable_name> = (val1, val2, val3, ..., valn)

Examples

t1 = ('Apple', 'Mango', 'Orange')
t2 = (10, 20, 30)

Types of Tuples

1. Empty Tuple

t1 = ()

2. Heterogeneous Tuple

t1 = ('Apple', 100, 23.25, 'Python') # different data types

3. Nested Tuple

t1 = ((1, 2, 3), (10, 20, 30, 40, 50))

4. List within Tuple

t1 = ([1, 2, 3], [4, 5, 6])

5. Mixed Nested Tuple

t1 = ((0, 1, 2, 3), ['a', 'b', 'python']) # Tuple and list inside a tuple

6. Parentheses are not mandatory

t1 = 10, 20, 30

Key Points:

  • Iterating through a tuple is faster compared to list
  • If we have data that is not required to be changed, storing it in a tuple ensures it won't be changed accidentally

Tuple Creation

1. Basic Tuple Creation

>>> t1 = (10, 20)
>>> t1
(10, 20)

2. Empty Tuple

>>> t1 = ()
>>> t1
()

3. Without Parentheses

>>> t1 = 10, 20, 30  # Parentheses are not mandatory
>>> t1
(10, 20, 30)

4. Mixed Data Types

>>> t1 = ('a', 10, 'python', [10, 20, 30], (1, 2, 3))
>>> t1
('a', 10, 'python', [10, 20, 30], (1, 2, 3))

5. Singleton Tuple

>>> t1 = (10,)  # Note the comma - important for single element tuple
>>> t1
(10,)

6. Using tuple() Function

>>> t1 = tuple()
>>> t1
()

>>> t1 = tuple(("python", "programming"))
>>> t1
('python', 'programming')

Accessing and Traversing Tuples

A tuple is a sequence of values which can be of any type and they are indexed by integers. Like lists, there could be positive indexing (0, 1, 2, ...) or negative indexing (-1, -2, -3, ...).

Positive Index0123456
tuple1023128745931000
Negative Index-7-6-5-4-3-2-1
>>> t1 = (120, 34, 56, 73, "python")
>>> t1[0]
120
>>> t1[-1]
'python'
>>> t1[-4]
34
>>> t1[4]
'python'
>>> t1[7]
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    t1[7]
IndexError: tuple index out of range

Traversing a Tuple

1. Using 'in' operator with for loop

a = (1, 2, 3)
for i in a:
    print(i)

Output:
1
2
3

2. Using range() function

a = (1, 2, 3)
l = len(a)
for i in range(l):
    print(a[i])

Output:
1
2
3

3. Using while loop

a = (1, 2, 3)
L = len(a)
i = 0
while i < L:
    print(a[i])
    i = i + 1

Common Tuple Operations

1. Tuple Slicing

2. Tuple Addition/Concatenation

3. Tuple Multiplication/Repetition

4. Membership Operators

4.1 Tuple Slicing

Slicing is used to retrieve a subset of values. A slice of a tuple is basically its sub-tuple.

Syntax:

Tuple_name[start:stop:step]
  • Start: starting point
  • Stop: stopping point (excluded)
  • Step: step size (stride)
>>> t1 = (1, 2, 3, 4, 5)
>>> t1[1:3]
(2, 3)
>>> t1[0:4]
(1, 2, 3, 4)
>>> t1[3:]
(4, 5)
>>> t1[:4]
(1, 2, 3, 4)
>>> t1[::-1]
(5, 4, 3, 2, 1)
>>> t1[2::-1]
(3, 2, 1)
>>> t1[2::-2]
(3, 1)

4.2 Tuple Addition/Concatenation (+)

Python allows you to join/concatenate two tuples. New elements can be added to a tuple using the '+' operator.

>>> x = (1, 2, 3)
>>> y = (10, 20, 30)
>>> x + y
(1, 2, 3, 10, 20, 30)

>>> z = x + y
>>> z
(1, 2, 3, 10, 20, 30)

>>> z[1:5] + x
(2, 3, 10, 20, 1, 2, 3)

>>> z[0:3] + x[1:2]  # x[1:2] is a tuple (2,)
(1, 2, 3, 2)

Key Points:

  • tuple + tuple → concatenates
  • tuple + int → error (incompatible types)
  • x[1:2] is a tuple slice (2,), while x[1] is an integer 2

4.3 Tuple Multiplication/Repetition (*)

The multiplication operator (*) is used for repetition of the tuple.

>>> t = (1, 2, 4, 7)
>>> t * 3
(1, 2, 4, 7, 1, 2, 4, 7, 1, 2, 4, 7)

>>> 2 * t
(1, 2, 4, 7, 1, 2, 4, 7)

>>> (1, 2, 8, 9) * 2
(1, 2, 8, 9, 1, 2, 8, 9)

>>> 2 * (10, 20)
(10, 20, 10, 20)

Key Points:

  • Tuple * int → repetition
  • int * tuple works same as tuple * int
  • Tuple * Tuple → NOT allowed

4.4 'in' and 'not in' Membership Operators

The 'in' operator checks whether a given element is contained in a tuple. It returns True if the element is present, otherwise False.

>>> 4 in (1, 2, 3, 4, 56)
True

>>> 40 in (1, 2, 3, 4, 56)
False

>>> t1 = (1, 2, 3, 4, 5, 6)
>>> 2 in t1
True

>>> 20 in t1
False

>>> 2 in t1[0:3]  # t1[0:3] = (1, 2, 3)
True

# Using 'not in' operator
>>> t1 = (1, 2, 3, 4, 5)
>>> 21 not in t1
True

>>> 2 not in t1
False

4.5 Comparing Tuples

Tuples can be compared using operators <, >, ==, != etc. While comparing, int and float are considered the same.

>>> (1, 2, 3) > (0, 1, 2)
# Compare first elements: 1 > 0 → True
True

>>> (0, 1, 20000) < (0, 3, 4)
# First elements: 0 == 0 → move to next
# Second elements: 1 < 3 → True
True

>>> (1, 2, 3) == (1, 2, 3)
# All elements are equal → True
True

>>> (1, 2, 3) != (1, 2, 4)
# First two elements equal, last differs → True
True

>>> (2, 5) < (2, 5, 0)
# First two elements equal, but left tuple is shorter → True
True

>>> (10, 1) > (2, 1000)
# First element 10 > 2 → True
True

5. Packing and Unpacking Tuples

>>> t = (1, 2, 3, 4, 5)
>>> t1 = list(t)
>>> t1.append(100)
>>> t = tuple(t1)
>>> t
(1, 2, 3, 4, 5, 100)

6. Deleting a Tuple

The del statement is used to delete a tuple.

>>> t1 = (1, 2, 3)
>>> t1
(1, 2, 3)
>>> del t1
>>> t1
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    t1
NameError: name 't1' is not defined

Advantages and Disadvantages of Tuples

✅ Advantages

  • Immutable: Once created, no one can accidentally change it. Perfect for safe and fixed data.
  • Fast and lightweight: Take up less memory and work faster than lists.
  • Dictionary keys: Can be used as keys in dictionaries or elements in sets.
  • Data integrity: Best for storing information that should never be modified.

❌ Disadvantages

  • Cannot be changed: Need to convert to list first for modifications.
  • Limited methods: Only have two built-in methods (count() and index()).
  • Less flexible: If data changes often, lists are more convenient.
  • Extra steps: Any modification requires creating a whole new tuple.

Chapter: Dictionary

1. Introduction

A Dictionary is a collection in Python which is known as a mapping between keys and values.

Python dictionary is an unordered collection of items where each item is a key-value pair.

We can also refer to a dictionary as a mapping between a set of keys/indices and a set of values.

Syntax

{"key": "values"}
{"key1": "values1", "key2": "values2", ..., "keyn": "valuesn"}

One item: "key": "value"

Important Features of Dictionary

  1. Each key maps to a value. The association of a key and value is called a key-value pair.
  2. Each key is separated from its value by a colon (:), items are separated by commas, and the entire dictionary is enclosed in curly braces .
  3. Keys are unique within a dictionary while values may not be.
  4. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
  5. Dictionary is mutable. We can add new items or change the value of existing items.

2. Creating a Dictionary

Basic Dictionary Creation

Syntax: <Dict_name> = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

>>> a = {"one": 10, "two": 20}
>>> a
{'one': 10, 'two': 20}

>>> a = {"one": 10, "one": 20}  # Duplicate keys - last value wins
>>> a
{'one': 20}

>>> a = {"one": 10, "two": 20, 1: "three", 10: 345, 3: 34.25}
>>> a
{'one': 10, 'two': 20, 1: 'three', 10: 345, 3: 34.25}

Empty Dictionary

>>> dic = {}
>>> dic
{}
>>> type(dic)
<class 'dict'>

Using Built-in Function dict()

>>> a = dict()
>>> a
{}

3. Accessing Elements in Dictionary

Syntax:

Dictionary_name[key]
>>> d = {"one": "1", 2: "two"}
>>> d["one"]
'1'
>>> d[2]
'two'
>>> d[3]
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    d[3]
KeyError: 3

4. Traversing a Dictionary

Traversing a dictionary means accessing each key, value, or both one by one. In Python, you can do this using a for loop in different ways:

Using 'in' operator with for loop

my_dict = {'name': 'Athis', 'subject': 'CS', 'marks': 100}
for key in my_dict:
    print(key)

Output:
name
subject
marks

Key Point for Exams:

Why we use a for loop with dictionaries (and not while directly):

  • for key in dict: is valid because a dictionary is iterable (uses in)
  • There's no "direct index-based for loop" like in arrays
  • while is not direct because it needs an index, which dictionaries don't have

5. Appending Values to a Dictionary

We can add new elements to the existing dictionary, extend it with single pair of values or join two dictionaries into one.

Syntax:

Dictionary_Name[Key] = values
>>> d1 = {'mon': "MONDAY", 'tue': "TUESDAY", 'wed': "WEDNESDAY"}
>>> d1['thu'] = "THURSDAY"
>>> d1
{'mon': 'MONDAY', 'tue': 'TUESDAY', 'wed': 'WEDNESDAY', 'thu': 'THURSDAY'}
>>> d1['fri'] = "FRIDAY"
>>> d1
{'mon': 'MONDAY', 'tue': 'TUESDAY', 'wed': 'WEDNESDAY', 'thu': 'THURSDAY', 'fri': 'FRIDAY'}

6. Updating Elements in a Dictionary

You can update a dictionary by modifying existing key-value pairs or by merging another dictionary with an existing one.

Syntax:

Dictionary_Name['key'] = 'Values'
>>> d2 = {'Teena': 18, 'Riya': 12, 'Alya': 22}
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 22}
>>> d2['Alya'] = 10
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10}

>>> d1 = {1: "one", 2: "two"}
>>> d2.update(d1)
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10, 1: 'one', 2: 'two'}

>>> d3 = {100: "String"}
>>> d2.update(d3)
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10, 1: 'one', 2: 'two', 100: 'String'}

Key Points:

  • Dictionaries change in place: You don't create a new one — you just modify the old one
  • If key exists → value changes; if key doesn't exist → new pair is added automatically
  • You can also use .update() method: student.update({'marks': 98, 'age': 17})

7. Removing an Item from Dictionary

We can remove an item from the existing dictionary by using del command or using pop() method.

Using del command

Syntax:

del dicname[key]
>>> d1 = {1: 100, 2: 200, 3: "three", 23.34: [1, 2, 3]}
>>> del d1[23.34]
>>> d1
{1: 100, 2: 200, 3: 'three'}
>>> del d1[2]
>>> d1
{1: 100, 3: 'three'}
>>> del d1[100]
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    del d1[100]
KeyError: 100

Using pop() method

Pop() method will not only delete the item from the dictionary but also returns the deleted value.

Syntax:

dictname.pop(key)
>>> d1
{1: 100, 3: 'three'}
>>> d1.pop(1)
100
>>> d1
{3: 'three'}

8. 'in' and 'not in' Membership Operators

The "in" operator checks whether a particular key is there in the dictionary. It returns true if the element appears in the dictionary, otherwise returns false.

>>> d1 = {1: 100, 2: 200, 3: "three", 23.34: [1, 2, 3]}
>>> d1
{1: 100, 2: 200, 3: 'three', 23.34: [1, 2, 3]}
>>> 1 in d1
True
>>> 200 in d1          # 200 is a value, not a key
False
>>> "three" in d1      # "three" is a value, not a key
False
>>> 23.34 in d1
True
>>> 1 not in d1
False

Key Points:

Membership operators in and functions like min(), max() and sum() apply only to the keys in a dictionary.

9. Common Dictionary Functions and Methods

9.1 len() - Count the Elements

This method returns the number of key-value pairs in the given dictionary. Count starts from 1.

Syntax:

len(dictionary_name)
>>> d1 = {1: 100, 2: 200, 3: "three", 23.34: [1, 2, 3]}
>>> len(d1)
4

9.2 clear()

It removes all items from the particular dictionary.

Syntax:

d1.clear()
>>> d1
{1: 100, 2: 200, 3: 'three', 23.34: [1, 2, 3]}
>>> d1.clear()
>>> d1
{}

9.3 get()

The get method returns a value for the given key. If key is not available then returns default value None.

Syntax:

d1.get(key, default=None)
  • Key: This is the key to be searched in the dictionary
  • Default: This is a value to be returned in case the key does not exist
# Creating dictionary
d1 = {'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
print("Original Dictionary:", d1)

# 1. Getting existing key
print("d1.get('sun') ->", d1.get('sun'))   # Returns 'SUNDAY'

# 2. Getting a missing key (no default given)
print("d1.get('fri') ->", d1.get('fri'))   # Returns None

# 3. Getting missing key with your own default value
print("d1.get('fri','never') ->", d1.get('fri','never'))  # Returns 'never'

# 4. Getting existing key with default given
print("d1.get('mon','never') ->", d1.get('mon','never'))  # Returns 'MONDAY'

# 5. Getting missing key with None explicitly
print("d1.get('fri', None) ->", d1.get('fri', None))      # Returns None

9.4 items()

It returns the content of the dictionary as a list of tuples having key-value pairs.

Syntax:

d1.items()
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.items()
dict_items([('sun', 'SUNDAY'), ('mon', 'MONDAY'), ('tue', 'TUESDAY')])

9.5 keys()

It returns a list of the key values in a dictionary.

Syntax:

d1.keys()
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.keys()
dict_keys(['sun', 'mon', 'tue'])

9.6 values()

It returns a list of values from key-value pairs in a dictionary.

Syntax:

d1.values()
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.values()
dict_values(['SUNDAY', 'MONDAY', 'TUESDAY'])

9.7 fromkeys()

This function is used to create a dictionary from a collection of keys (tuple/list).

Syntax:

dict.fromkeys(keys, value)
>>> keys1 = [1, 2, 3]; values1 = 1000
>>> d1 = dict.fromkeys(keys1, values1)
>>> d1
{1: 1000, 2: 1000, 3: 1000}

>>> keys2 = [1, 2, 3]; values2 = "Undefined"
>>> d1 = dict.fromkeys(keys2, values2)
>>> d1
{1: 'Undefined', 2: 'Undefined', 3: 'Undefined'}

>>> keys2 = [1, 2, 3]
>>> d1 = dict.fromkeys(keys2)
>>> d1
{1: None, 2: None, 3: None}

9.8 copy()

This method creates a copy of a dictionary.

Syntax:

Dictionary_name.copy()
>>> d1
{1: None, 2: 2900, 3: None}
>>> d2 = d1.copy()
>>> d2
{1: None, 2: 2900, 3: None}

9.9 popitem()

This method removes the last item from the dictionary and returns this deleted item.

Syntax:

Dictionary_name.popitem()
>>> d2
{1: None, 2: 2900, 3: None}
>>> d2.popitem()
(3, None)
>>> d2
{1: None, 2: 2900}

9.10 setdefault()

This method returns the value of the item with the specified key. If the key does not exist, it inserts the key with the specified value.

Syntax:

<Value> = <Dict>.setdefault(<key>, <default_value>)

The setdefault returns:

  1. Value of the key, if it is in the dictionary
  2. None, if key is not in the dictionary and default_value is not specified
  3. Default_value, if key is not in the dictionary and default value is specified
>>> d = {'Name': "Athishta", "Gender": "Female"}
>>> a = d.setdefault('Name')
>>> a
'Athishta'

>>> a = d.setdefault('Name', "Name not available")
>>> a
'Athishta'

>>> a = d.setdefault('Gender', "Gender not available")
>>> a
'Female'

>>> a = d.setdefault('Age', "Age not available")
>>> a
'Age not available'

9.11 max() and min()

The max() method returns the key having maximum value. On the contrary, min() returns the key having minimum value.

Syntax:

max(dict_name)
min(dict_name)
d = {'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
print(max(d))  # tue  (alphabetically largest key)
print(min(d))  # mon  (alphab  'tue': 'TUESDAY'}
print(max(d))  # tue  (alphabetically largest key)
print(min(d))  # mon  (alphabetically smallest key)

d2 = {1: "one", "two": 2}
>>> max(d2)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    max(d2)
TypeError: '>' not supported between instances of 'str' and 'int'

d1 = {"a": 100, "b": 50, "c": 85, "d": 65}
>>> max(d1)
'd'
>>> min(d1)
'a'

9.12 sorted()

This method sorts the elements of a dictionary by its keys or values.

Syntax:

sorted(d1)
>>> d1 = {"a": 100, "b": 50, "c": 85, "d": 65}
>>> a = sorted(d1)
>>> a
['a', 'b', 'c', 'd']

>>> y = sorted(d1.values())
>>> y
[50, 65, 85, 100]

>>> z = sorted(d1.items())
>>> z
[('a', 100), ('b', 50), ('c', 85), ('d', 65)]

10. Tuple vs Dictionary Comparison

FeatureTupleDictionary
DefinitionOrdered collection of elementsCollection of key–value pairs
Syntax(1, 2, 3){'a': 1, 'b': 2}
MutabilityImmutable (cannot be changed)Mutable (can add, update, delete items)
Access methodAccess by index (e.g. t[0])Access by key (e.g. d['a'])
DuplicatesAllows duplicate elementsKeys must be unique (values can repeat)
OrderingMaintains order of elementsMaintains insertion order (Python 3.7+)
Use caseFixed data that shouldn't changeData that needs quick lookups by keys
Methods availableVery few (count(), index())Many (get(), update(), keys(), etc.)

Related Resources

Need Help?

Join our tuition classes for personalized guidance on Python programming.

Register for Classes →

Practice More

Try string manipulation exercises to strengthen your Python skills.

View Practical Programs →