Python Data Structures: Dictionaries & Tuples¶

Ahmed Moustafa

Dictionaries¶

  • A dictionary is an unordered collection of key-value pairs.
  • Each key is unique and maps to a value.
  • The syntax for creating a dictionary is:
In [2]:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict
Out[2]:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

You can access values in a dictionary using their keys:

In [3]:
print(my_dict["key1"])
value1

Example¶

In [4]:
states = {}                  # Create empty dict
states['ca'] = 'California'  # 1. Set key/value pairs into dict
states['ok'] = 'Oklahoma'
states['nj'] = 'New Jersey'
states['tx'] = 'Texas'
states
Out[4]:
{'ca': 'California', 'ok': 'Oklahoma', 'nj': 'New Jersey', 'tx': 'Texas'}
In [5]:
type(states)
Out[5]:
dict

Source: Nick Parlante's Python guide

Dictionary commonly used functions¶

  • keys(): Returns a list of all the keys in the dictionary
  • values(): Returns a list of all the values in the dictionary
  • items(): Returns a list of all the key-value pairs in the dictionary
In [7]:
phonebook = {"Alice": "555-1234", "Bob": "555-5678", "Charlie": "555-9012"}
phonebook
Out[7]:
{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}
In [8]:
print(phonebook["Alice"])
555-1234
In [9]:
print(phonebook.keys())
dict_keys(['Alice', 'Bob', 'Charlie'])
In [10]:
print(phonebook.values())
dict_values(['555-1234', '555-5678', '555-9012'])
In [11]:
print(phonebook.items())
dict_items([('Alice', '555-1234'), ('Bob', '555-5678'), ('Charlie', '555-9012')])
In [12]:
phonebook["John"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[12], line 1
----> 1 phonebook["John"]

KeyError: 'John'

Tuples¶

  • A tuple is an ordered collection of values.
  • Tuples are immutable, meaning you can't modify their values once they're created.
  • The syntax for creating a tuple is:
In [ ]:
my_tuple = ("value1", "value2", "value3")
my_tuple

You can access values in a tuple using their index:

In [ ]:
print(my_tuple[0])

Tupples commonly used functions:¶

  • count(): Returns the number of times a value appears in the tuple
  • index(): Returns the index of the first occurrence of a value in the tuple
In [ ]:
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
days_of_week
In [ ]:
print(days_of_week[0])
In [ ]:
print(days_of_week.count("Monday"))
In [ ]:
print(days_of_week.index("Wednesday"))

Differences between Dictionaries and Tuples¶

  • Dictionaries and tuples are used for different purposes.
  • Dictionaries are used to map unique keys to values, while tuples are used to store collections of values.
  • Dictionaries are mutable, while tuples are immutable.
  • Dictionaries are unordered, while tuples are ordered.

More Example¶

Storing information about a person, such as their name, address, and phone number:

In [ ]:
person = {"name": "Jane Doe", "address": "123 Main St", "phone": "555-1234"}
person

Storing a dictionary of translations between different languages:

In [ ]:
translations = {"hello": {"spanish": "hola", "french": "bonjour"}}
translations

Representing a point in two-dimensional space:

In [ ]:
point = (3, 5)
point

Storing the RGB color values for a particular color:

In [ ]:
color = (255, 128, 0)
color

Exercise: Factorial¶

Factorial is a mathematical function that is represented by an exclamation mark (!). It is used to find the product of all positive integers from 1 to a given number. For example, the factorial of 5 (represented as 5!) is calculated as 5 x 4 x 3 x 2 x 1, which equals 120. In other words, factorial is the multiplication of all positive integers up to a given number.

Write a program that calculates the factorial of 5.

In [ ]:
# Solution: Factorial