Python: Dictionaries
Python Dictionaries
1 Overview
📘 Dictionaries in Python
Python dictionaries are mutable, ordered, and built-in data structures that store data as key-value pairs. Each key in a dictionary is unique and immutable, meaning it can be of types such as strings, numbers, or tuples, but not mutable types like lists. Values associated with keys can be of any data type and duplicates are allowed. Dictionaries are mutable, so their contents can be changed after creation by adding, updating, or removing key-value pairs.
Dictionaries are unordered in versions before Python 3.7, but from Python 3.7 onward, they maintain insertion order. Internally, dictionaries use a hash table to provide efficient operations such as lookup, insertion, and deletion with average constant time complexity. Keys must be hashable to enable this hashing mechanism. The structure is typically defined using curly braces where each key is separated from its value by a colon, and pairs are separated by commas.
Dictionaries can be created using literals with curly braces, the dict() constructor, or comprehensions. They are versatile for associating data where keys serve as unique identifiers for their values, facilitating fast data retrieval and modification.
2 Dictionaries
2.1 Without dictionaries (option 1)
- Suppose you want to store student names with their grades.
- One option is to have two parallel lists:
2.2 Problems
- You need two lists in sync → easy to mess up if one changes.
- Finding Bob’s grade requires searching (
.index()), which is O(n). - Readability suffers — you always have to remember which list matches what.
- Imagine storing more fields: email, surname, address…
2.3 Without dictionaries (option 2)
- Another option is to group students in sublists:
2.4 Problems
- All sublists must follow the same order:
[name, grade]. - Finding Bob’s grade requires searching in O(n) again.
- Still not very readable — you have to remember
record[0]is the name. - Imagine storing more fields: email, surname, address…
3 Dictionaries
- Dictionaries (abbreviated as dicts) are mutable collection of key-value pairs.
Get value of specific key:
1
- Now the student grades’ code is more clear and efficient (O(1) on average):
- With more fields we could do something like a dict of dicts:
4 Consider
- Keys have to be unique and of an immutable type (e.g.,
int,string,tuple). - Values can have any type.
- Creating a dictionary with a mutable key type gives error.
- With tuples it works just fine.
- Values are overlapped if keys are the same, keeping the last one:
- Use keys for accessing, updating and creating dict values:
- If the key does not exist, it crashes:
5 Multiple types
‘hola’
[1, 2, 3]
---
## Functions
- Common built-in functions: `len()`.
```python
my_dict = {'key1': 1, 'key2': 2, 'key3': 3}
print(len(my_dict))
6 Methods
Dictionary methods: https://www.w3schools.com/python/python_ref_dictionary.asp
keys(): Returns a view object displaying a list of all the keys in the dictionary.
[‘key1’, ‘key2’, ‘key3’]
values(): Returns a view object displaying a list of all the values in the dictionary.
[1, 2, 3]
items(): Returns a view object displaying a list of the dictionary’s key-value pairs as tuples.
[(‘key1’, 1), (‘key2’, 2), (‘key3’, 3)]
- As dictionaries are mutable, changing one of the them affects the other:
copy(): This method returns a shallow copy of the dictionary.
- Update a dictionary with another dictionary with
.update() - In case they have equal keys, the keys of the dict given in the update are used.
- Accessing a non-existen key with indexing gives an error.
- Avoid this error with
.get(), as it returnsNoneby default. - Optionally, a default value can be specified if the key does not exist.
None
0
7 in
- The
inkeword can be used to verify if a key is found in a dictionary.
False
8 Iteration
- Typically iterate through tuples of (key, value) pairs with
.items():
The key is key2 and the value is 2.
The key is key3 and the value is 3.
- Or keys only:
The key is key2 and the value is 2.
The key is key3 and the value is 3.
- Or values only:
The value is 2.
The value is 3.
9 Comprehension
- Similar to lists, tuples and sets:
10 Empty
- By default, an empty
{}in Python is an empty dictionary, not an empty set!
- If we want to create an empty set:
11 Example
Given a string, create a dictionary with the frequency of each word in the string.
text = "one two three four three two one and one"
# Create empty dictionary for word frequency
word_frequency = {}
# Split text into words and iterate over each word
for word in text.split(' '):
# Add word to dictionary if it doesn't exist with a
# default value of 0, otherwise increment count
word_frequency[word] = word_frequency.get(word, 0) + 1
print(word_frequency)