dictionary-data-structure

Python Dictionary Data Structure Practical Example

Last Updated | Feb, 13, 2021 By Kingsley Ijomah
In this tutorial, you'll learn about Python's Dictionary data structure. You'll look at some of the best scenarios to use it and finally, we will visit the dictionary data structure's methods with sample codes.

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.

  • Order might be important
  • Need to access an element by known unique keys
  • Want to be able to modify elements

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

Creating Python Dictionary

code
# 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'}

Access Dictionary Values

You can access values of a dictionary using the keys either by calling [ ] or using get( ) method.

code
# creat a dictionary
student = {'name': 'Kingsley', 'age': 37}


# access with []
student['name'] # output => 'Kingsley'


# access using get()
student.get('age') # output => 37

Dictionary elements

Because dictionaries are mutable we can change them, let's have a look at some examples

code
# Changing Dictionary Elements
student = {'name': 'Kingsley', 'age': 37}

# update value
student['age'] = 26

print(student) # => {'name': 'Kingsley', 'age': 26}

Remove Element From Dictionary

Let's see some examples of removing elements from dictionary

code
# 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

Dictionary Membership Test

We can check if a key is available in a dictionary using the in keyword, let's see how that is used

code
# Membership Test for Dictionary Keys
student = {'name': 'Kingsley', 'age': 37}


print('name' in student) #output => True


print('name' not in student) #output => False

Dictionary Code Challenge

Let's explore a typical case when the dictionary data structure comes in handy.

School Roster Example

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:

  • Store a list of name and grade dictionary structure
  • Sort by grade and name
  • return result as a list
code
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.

MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.

Learn To Code With Me.
FREE course included.

GET IN TOUCH

Enter your email address:

Delivered by FeedBurner