time to read 7 min read

Python Dictionaries

Before Google became the go to for word search, we used dictionaries. Dictionaries helped us figure out the meaning of words and add information about them. Python dictionaries are similar. They have keys (which can be compared to words) and values (which can be compared to the “a word’s” meaning).

A dictionary is a collection of items wrapped around by curly braces. Those items are referred to as key and value pairs.

Properties of Python Dictionaries

  • All its items are encapsulated in curly braces {}
  • Each item in a dictionary must have a key and a value.
  • A key is a unique element, it can be a string or integer (an example of a key is a student’s name) 
  • A value provides additional information about a key, it can be a string (a text wrapped around in quotation marks), an integer (whole numbers), floating numbers (have decimal values), a boolean (they are either true or false), a list (items separated with a comma in a square bracket) or even another dictionary. An example of a value is a student’s age
  • A key and a value are separated by a colon(:)
key : value
  • If there are other keys and values, they are separated by a comma(,)
key : value,
key1 : value1,
key2: value2

There is no need to put a comma at the end of the last value.

Creating a Dictionary

There are two methods of creating a dictionary; using the curly braces and using the dict() 

Curly Braces

We will create a variable that will store a dictionary

  • First, create a variable name 
  • Then use the assignment operator (=) 
  • lastly, put the curly braces after the operator
my_first_dictionary = {}
# This is called an empty dictionary because nothing is stored in it
  • Using the type() method, it checks what type of data the variable is:
print(type(my_first_dictionary))

# output
# <class 'dict'>

Creating a dictionary with items

my_first_dictionary = {"Character Name": "Smolder Bravestone"}

Using the built-in dict() function

  • First, create a variable name 
  • Then use the assignment operator (=) 
  • Afterwards, type in the “dict()’’ keyword, 
  • Then print out the variable name
my_first_dictionary = dict()
print(my_first_dictionary)
# ouput
# {} an empty dictionary has no items present

Creating a dictionary with items

my_first_dictionary = dict({"Character Name": "Smolder Bravestone"})

Example: create a dictionary that stores the names of 5 students and their ages;

student_age = {"Bob": 12, "Helen": 14, "Lucy": 10, "Matt": 13, "Ella": 11}

# the keys are the name of students and data type is a string(‘text’) , the values are the ages of each student and the data type is an integer(‘whole numbers’)
# Ouput
{"Bob": 12, "Helen": 14, "Lucy": 10, "Matt": 13, "Ella": 11}

Examples of Dictionaries with different data types

Example I: with lists

about_me = {
  'Name': 'Karen Gillen',
  'Profession':'Actress',
  'Age': 30,
  'Popular Character': 'Ruby Roundhouse',
  'Strength':'Dance Fighting',
  'Weakness': 'Venom',
  'Popular Movies': ['Jumanji','Jumanji 2','Treasure Island']  
}

In the example above, we see that both the keys and values are strings, except one key that has its value as a list.

'Popular Movies': ['Jumanji','Jumanji 2','Treasure Island']  

Example II: with boolean

neighbour_pet = {
  'Animal': 'Dog',
  'Name': 'Bingo',
  'Fur color': 'White',
  'Barks': False,
  'Pees': True,
  'Friendly': True
}

In the example above, all the keys are strings while some of the values are strings and boolean. A boolean expression consists of True or false statements.

Example III: with floating numbers

grading_points = {
  'A': 90.55,
  'B': 80.45,
  'C': 70.35,
  'D': 60.25,
  'E': 50.15
}

In the example above, all the keys are strings while all the values are floating numbers

Accessing Items in a Dictionary

There are different ways of accessing elements stored in a dictionary.

Using keywords:

student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}
  • In the dictionary above, ‘the variable name is [student_age], the keys are the names (strings), and the values are the ages (integer).
  • Let’s say I want to print Bob’s age;
  • Since we want to access information in the dictionary, we take the variable name (student_age) and use indexing.
  • Indexing is a process of accessing elements in a list or dictionary using a particular value; for lists, they are integers, and for dictionaries, they are keywords.

They have this format;

variable_name[keyword]
# variable_name is the variable that stores the dictionary
# keyword is the item we are looking for in the dictionary it can be a string or an integer
# The variable name is “student_age” and the keyword is “Bob”

print(student_age['Bob'])
# ouptut
# 12
  • I put the output in a formatted string to make it much better. The formatted strings enable me to add text to a variable without using the “+” sign (concatenation). To write a formatted string, you type the letter(f) and two quotation marks in front. [f” “], a variable is placed in curly braces.
print("Bob is " + str(student_age["Bob"]) + "years old")

# output
# Bob is 12 years

In concatenation, you must convert the integer to a string because integers cannot be added to a string.

Note: When passing in the keyword, how they appear in the dictionary is how they should be passed. We see above (‘Bob’) has its first letter in a capital letter; if we pass in the small letter b, it throws an error.

student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

print(student_age['bob'])

# output
# KeyError: 'bob'

Using Loops

We use the for loop to access all elements in the dictionary. In for loops, we pass in one variable to get the ‘keys’ and use indexing to get the ‘values.’       

student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

for name in student_age:
      age = student_age[name]
      print(name)
      print(age)

#output
#Bob
#12
#Helen
#14
#Lucy
#10
#Matt
#13
#Ella
#11
  • The information in the variable “student_age” is in two parts; the left side consists of the keys holding the names of students, while the right side consists of the values corresponding to the keys that are the ages of the students.
  • Looping through the new variable, <name>, it stores the items accessed in the loop. The ‘name’ variable stores the keys.
  • To access the values corresponding to the keys, we use indexing.
  • The variable name is <student_age> and the keyword is the variable <name>
  • Then we create a new variable <age> to store the values. 
  • Last, we print <name> and <age>

Note: the variable in the loop you use to access the keys can be any name of your choice.

  • the keyword in this indexing is a new variable, not a string, so there is no need to wrap it with quotation marks

Adding items in a Dictionary

In lists, when we want to add items to the existing information, we use the “append” method. In dictionaries, we pass in the keyword in square brackets and assign the value making the variable name a reference point.

student_age = {
 'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

Let’s say we want to add a new student’s name and age to this existing information and print the new dictionary. We take the following steps;

  • Since we are introducing changes to the existing dictionary above, we take the variable name <student_age> and make use of indexing.
  • Indexing is a process of accessing elements in a list or dictionary using a particular value; for lists, they are integers, and for dictionaries, they are keywords.
  • They have this format: variable_name[keyword]
  • Then put the assignment operator(=), type in the details of the keyword (value)
  • Lastly, you print the variable that stores the dictionary to see the updated information.
# Format
student_age["Mario"] = 12
print(student_age)

# output
{"Bob": 12, "Helen": 14, "Lucy": 10, "Matt": 13, "Ella": 11, "Mario": 12}

How to change Values Using Indexing

Just like we use indexing to find a value and add new keys and values, we can also change some values using the same method. 

student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

student_age['Bob'] = 15
print(student_age)

# output 
{'Bob': 15, 'Helen': 14, 'Lucy': 10, 'Matt': 13, 'Ella': 11}

Lists Versus Dictionaries

A list stores items in a square bracket, while a dictionary stores pairs of items in curly braces. 

Similarities

  • They both store different data types like strings and integers.
  • Their items can both be accessed by loops.
  • Their items can be deleted, and new items can be added to both lists and dictionaries
  • Their items can be accessed with the indexing method

In lists

scores = [20, 40, 50, 60, 12]
print(scores[0])

# output
20

In dictionaries

award_winning_author = {
  'Author': 'C.S Lewis',
  'Book Title': '100 shades of awesomeness'
}
print(award_winning_author['Author'])

# output
C.S Lewis

Methods In Dictionaries

Methods are built-in functions that make code execution simpler. 

For example the sum() method adds all elements in a list, or max() method finds the maximum numbers in a list. Many methods aid our work with dictionaries. Some of them are;

  1. Clear: this method wipes out all items in a dictionary, returning an empty dictionary <{}>. We type the variable name and add <.clear()> method.
student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

student_age.clear()
print(student_age)

# output
# {} <- this is an empty dictionary, no items in it
  1. Get: This method finds a particular keyword and returns the corresponding value. It works like indexing but uses <.get()> instead of the square brackets<[]>.
student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

print(student_age.get('Bob'))

# output
12
  1. Pop: This method removes items from a dictionary but returns the corresponding value.
grades = {
40 : "Fail"  ,
90 :  "Excellent",
70 :  "Good"
}

grades.pop(40)
print(grades)

# output
{90: 'Excellent', 70: 'Good'}
  1. dict keys(): this method prints all the keys in the dictionary; they are the items on the left-hand side. The format is dict.keys() where “dict” is the name of the variable that stores the dictionary and .keys() is a method.
student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

print(student_age.keys())

# output
dict_keys(['Bob', 'Helen', 'Lucy', 'Matt', 'Ella'])
  1. dict.values(): this method prints all the values in the dictionary; they are the items on the right-hand side. The format is dict.values() where “dict” is the name of the variable that stores the dictionary and .values() is a method.
  1. dict.items(): this method returns both the keys and the values simultaneously. The keys are values are wrapped around in a parenthesis ()- called tuples and enclosed in a square bracket. 

The format is <dict.items()>, where <dict> is the name of the variable that stores the dictionary and < .items()> is a method.

student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

print(student_age.items())

# output
dict_items([('Bob', 12), ('Helen', 14), ('Lucy', 10), ('Matt', 13), ('Ella', 11)])
  1. Update: this method adds new items to the dictionary and also changes values that existed in the dictionary. The format is <variable_name.update(key = value)> where the <variable_name> stores the dictionary, <key> are the items on the left side while <value> are the items on the right side.
student_age = {
  'Bob': 12,
  'Helen' : 14,
  'Lucy': 10,
  'Matt':13,
  'Ella': 11
}

student_age.update(Bob=15)
print(student_age)

#output 
#15

Conclusion

Congratulations, this was a long read, but you made it to the end, and now you know how to work with python dictionaries. Remember to take learning in bits and celebrate your progress along the way. To know more about python lists and other data structures, check here.