Python dictionary as of Python 3.7 are ordered collection of key/value pair, imagine this to be an address book where you need to know a person name (key) in order to retrieve their full information.
When to use Dictionary
Below are some reasons why you might need to use the dictionary
data structure instead.
This article is a continuation of Python Data Structures For Beginners
Let us explore dictionary in more details... and in the end, solve a problem using dictionary
data structure.
Topics covered in this post:
1. Creating a Python Dictionary
2. Access Dictionary Values
3. Dictionary elements
4. Remove Element From Dictionary
5. Dictionary Membership Test
6. Dictionary Code Challenge
# empty dictionary
dict = {}
# dictionary with key and value
dict = {'name': 'Kingsley', 'age': 37}
# list of tuples into dictionary
dict = dict([(1,'car'), (2,'bicycle')]) # output => {1: 'car', 2: 'bicycle'}
You can access values of a dictionary using the keys either by calling [ ]
or using get( )
method.
# creat a dictionary
student = {'name': 'Kingsley', 'age': 37}
# access with []
student['name'] # output => 'Kingsley'
# access using get()
student.get('age') # output => 37
Because dictionaries are mutable we can change them, let's have a look at some examples
# Changing Dictionary Elements
student = {'name': 'Kingsley', 'age': 37}
# update value
student['age'] = 26
print(student) # => {'name': 'Kingsley', 'age': 26}
Let's see some examples of removing elements from dictionary
# Removing elements from a dictionary
dict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
# remove the item with key 2
dict.pop(2)
print(dict) # => {1: 'one', 3: 'three', 4: 'four', 5: 'five'}
# remove item from end of dict
print(dict.popitem())
# clear all items
dict.clear()
# delete the dictionary itself
del dict
We can check if a key is available in a dictionary using the in
keyword, let's see how that is used
# Membership Test for Dictionary Keys
student = {'name': 'Kingsley', 'age': 37}
print('name' in student) #output => True
print('name' not in student) #output => False
Let's explore a typical case when the dictionary data structure comes in handy.
Given students names and grade, create a roster for a school, the roster should return all students ordered by their grade and name.
Solution Steps:
class School:
def __init__(self):
self.database = [] #e.g [{'name': 'Aimee', 'grade': 2}, {'name': 'James', 'grade': 1}..]
def add_student(self, name, grade):
self.database.append({'name':name, 'grade':grade})
def database_sorted(self):
return sorted(self.database, key=lambda v: [v['grade'], v['name']])
def roster(self):
return [record['name'] for record in self.database_sorted()]
school = School()
school.add_student(name="Aimee", grade=2)
school.add_student(name="James", grade=1)
school.add_student(name="Anna", grade=1)
school.add_student(name="Tim", grade=3)
# result ordered first by grade followed by name
print(school.roster()) #Output ['Anna', 'James', 'Aimee', 'Tim']
Conclusion
When you need to associate values to keys beyond a simple list example. e.g student record with multiple attributes ( name, age, height, grade...) then reach for dictionary data structure.