Dictionaries in Python#
A dictionary is a collection of key-value pairs, i.e. key:value
. Each key is unique and is used to access its corresponding value. Dictionaries are defined using curly braces {}
.
See also
Here is a basic example of a dictionary:
# Example of a dictionary
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
print(my_dict)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Accessing Elements#
You can access elements in a dictionary by using their keys. If the key does not exist, Python will raise a KeyError
.
# Accessing elements in a dictionary
print(my_dict['name'])
print(my_dict['age'])
Alice
25
# Accessing non-existing keys
print(my_dict['unknown'])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[3], line 2
1 # Accessing non-existing keys
----> 2 print(my_dict['unknown'])
KeyError: 'unknown'
Altering Elements#
You can alter elements in a dictionary by assigning a new value to an existing key, or add new key-value pairs by assigning a value to a new key.
# Altering elements in a dictionary
my_dict['age'] = 31
my_dict['city'] = 'Boston'
print(my_dict)
{'name': 'Alice', 'age': 31, 'city': 'Boston'}
Important Built-in Methods#
Here are some important built-in methods for dictionaries:
keys()
: Returns a view object with all the keys in the dictionary.values()
: Returns a view object with all the values in the dictionary.items()
: Returns a view object with all the key-value pairs in the dictionary.get(key)
: Returns the value for the specified key if it exists, else returnsNone
.
# Using built-in methods
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
age = my_dict.get('age')
print('Keys:', keys)
print('Values:', values)
print('Items:', items)
print('Age:', age)
Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['Alice', 31, 'Boston'])
Items: dict_items([('name', 'Alice'), ('age', 31), ('city', 'Boston')])
Age: 31
Using Dictionaries as Tables#
Dictionaries can also be used to store tabular data. For example, we can have a dictionary where the keys are column names and the values are lists of column data.
# Example of using dictionaries as tables
my_table = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
print(my_table)
{'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago']}
Dictionaries with variables#
It is also possible to store variables in a dictionary, which are evaluated when you access them
w1 = 5
h1 = 3
area1 = w1 * h1
w2 = 2
h2 = 4
area2 = w2 * h2
rectangles = {
"width": [w1, w2],
"height": [h1, h2],
"area": [area1, area2]
}
print(rectangles)
{'width': [5, 2], 'height': [3, 4], 'area': [15, 8]}
Exercise#
You just measured the radius of three circles. Write them into a table and add a column with corresponding circle area measurements.
r1 = 12
r2 = 8
r3 = 15