Learning Management Platform for Written Tutorial Series.

Python 3 Dictionary - With working examples

Python 3 Dictionary - With working examples

Python Dictionary

A dictionary in python is an array variable that pairs keys with values. It is similar to a list with the major difference being lists use index numbers while dictionaries use keys. In this lesson, we will teach you how to work with dictionaries in python.

Topics to be covered

In this lesson, we will cover the following topics

  • How to create dictionaries in python
  • Accessing items in a dictionary
  • Removing items from a dictionary
  • Adding items to a dictionary
  • Python dictionary comprehension
  • Python dictionary methods

How to create dictionaries in python

Dictionaries are created using curly brackets. Let's look at a simple example that creates a dictionary to hold student results.

results = {
    'maths':89,
    'chemistry':75,
    'biology':95,
    'physics':90
}

print(type(results))

print(results)

HERE,

  • results = {...} defines a dictionary that contains test score results
  • print(type(results)) prints the data type of the variable result
  • print(results) prints the value of the dictionary in the console

Executing the above code produces the following results.

<class 'dict'>
{'maths': 89, 'chemistry': 75, 'biology': 95, 'physics': 90}

Accessing items in a dictionary

In the above example, we created a list and just printed out everything in one line. We will now use a for loop to iterate through the results of the variable result.

Iterating through the dictionary keys

results = {
    'maths':89,
    'chemistry':75,
    'biology':95,
    'physics':90
}

#iterate through all the keys
print('the keys in our dictionary are')
for key in results:
    print(key)

HERE,

  • for key in results: extracts the keys from the dictionary and assigns them to the variable key.

Executing the above code produces the following results

the keys in our dictionary are
maths
chemistry
biology
physics

Python dictionary printing keys and values using for loop

Let's now print the keys and value

results = {
    'maths':89,
    'chemistry':75,
    'biology':95,
    'physics':90
}

#print keys and corresponding values
print('the keys and their values in our dictionary are\n')
for key in results:
    print(f'The score for {key} is {results[key]}')

HERE,

  • results[key] extracts the item from the list that matches the value of the key variable. For example, result['math'] returns the value of the key math.

Executing the above code produces the following results

the keys and their values in our dictionary are

The score for maths is 89
The score for chemistry is 75
The score for biology is 95
The score for physics is 90

Removing items from a dictionary

Let's now look at how we can remove items from a dictionary.

drinks = {
    'beer':'Castle',
    'vodka':'Russian Standard',
    'gin':'London Dry Gin',
    'rum':'Barcadi'
}

print(drinks)
item = drinks.pop('beer')
print(f'the item {item} has been removed from the dictionary')
print(drinks)

HERE,

  • drinks = {...} defines a dictionary variable
  • print(drinks) creates the value of drinks after we create it.
  • item = drinks.pop('beer') removes the item with the key of beer and the value Castle is assigned to the variable item
  • print(f'the item {item} has been removed from the dictionary') prints the value of the item that has been removed
  • print(drinks) prints the value of drinks after popping out one item

Executing the above code produces the following result

{'beer': 'Castle', 'vodka': 'Russian Standard', 'gin': 'London Dry Gin', 'rum': 'Barcadi'}
the item Castle has been removed from the dictionary
{'vodka': 'Russian Standard', 'gin': 'London Dry Gin', 'rum': 'Barcadi'}

Note: the last print out does not contain the item with the key of beer

You can also delete a key from a dictional using the del keyword like so

drinks = {
    'beer':'Castle',
    'vodka':'Russian Standard',
    'gin':'London Dry Gin',
    'rum':'Barcadi'
}

print(drinks)
del drinks['rum']
print(drinks)

HERE,

  • del drinks['rum'] deletes the key rum from our dictionary

Executing the above code produces the following results

{'beer': 'Castle', 'vodka': 'Russian Standard', 'gin': 'London Dry Gin', 'rum': 'Barcadi'}
{'beer': 'Castle', 'vodka': 'Russian Standard', 'gin': 'London Dry Gin'}

Adding items to a dictionary

Let's now look at how we can add items to a dictionary

arts = {
    'trivium':['Grammar','Logic','Rhetoric'],
    'quadrivium':['Arithmetic','Geometry','Astronomy','Music']
}

arts['remarks'] = 'Gone are the days when the liberal arts where central to university learning.'

print(arts)

HERE,

  • arts = {...} defines a variable arts that contains two keys namely trivium and quadrivium that each contain list values
  • arts['remarks'] adds a new key remarks with a string value
  • print(arts) prints out the value of arts

Executing the above code produces the following results

{'trivium': ['Grammar', 'Logic', 'Rhetoric'], 'quadrivium': ['Arithmetic', 'Geometry', 'Astronomy', 'Music'], 'remarks': 'Gone are the days when the liberal arts where central to university learning.'}

Note: the key remarks is included in our dictionary even if it was not their originally.

Let's now modify our example and print out the 7 liberal arts

arts = {
    'trivium':['Grammar','Logic','Rhetoric'],
    'quadrivium':['Arithmetic','Geometry','Astronomy','Music']
}

arts['remarks'] = 'Gone are the days when the liberal arts where central to university learning.'

for key in arts:
    print(key)

    if key == 'remarks':
        print(arts[key])
        continue

    for art in arts[key]:
        print(f'-{art}')

Executing our code above produces the following results

trivium
-Grammar
-Logic
-Rhetoric
quadrivium
-Arithmetic
-Geometry
-Astronomy
-Music
remarks
Gone are the days when the liberal arts where central to university learning.

Python dictionary comprehension

Dictionary comprehension allows us to create a new dictionary variables using simple expressions.

The syntax for dictionary comprehension is as follows

{key: expression for key in iterable}

HERE,

  • key defines the key that will be used in our dictionary
  • expression is the expression that will be evaluated to produce the value of the key
  • for key in iterable uses a for loop to iterate through list.

Let's look at a practical example. Suppose we have a list of numbers from 1 to 10 and we would like to square these numbers and use the numbers as keys to the squares. For example, for the number two, we will produce 2:4 where is the key and 4 is the value.

numbers = [1,2,3,4,5,6,7,8,9,10]

roots_squared = {n: n**2 for n in numbers}

print(roots_squared)

HERE,

  • roots_squared = {n: n**2 for n in numbers} sets the number that is extracted in the interation as the key and assigns the result of the expression n**2 as the value for the key. Our expression basically raises n to the power of 2. The result is assigned to the variable roots_squared
  • print(roots_squared) prints the results of roots_squared

Executing the above code produces the following results

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Python if condition in dictionary comprehension

It is also possible to include a condition in a dictionary comprehension.

The syntax is as follows

{key: expression for key in iterable if condition}

HERE,**

  • key defines the key that will be used in our dictionary
  • expression is the expression that will be evaluated to produce the value of the key
  • for key in iterable uses a for loop to iterate through list.
  • if condition sets the condition that should be true for our expression to be evaluated

Let's say we want to square only odd numbers. We can do it like so.

numbers = [1,2,3,4,5,6,7,8,9,10]

odds_squared = {x: x**2 for x in numbers if x % 2 != 0}

print(odds_squared)

HERE,

  • numbers = [1,2,3,4,5,6,7,8,9,10] defines a list of numbers
  • {x: x**2 for x in numbers if x % 2 != 0} evaluates the expression x**2 if the number is not even and assigns the result to the variable odds_squared

Executing the above code produces the following results

{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Python dictionary methods

Python dictionary objects have built-in functions that we can use to perform common operations. In this section, we will explore some of these methods

How to clear all the items in a dictionary

The following code shows you how you can clear all of the items in a dictionary

pets = {
    'cats':'Disliked',
    'dogs':'Liked',
    'snakes':'Loved'
}

print(pets)

pets.clear()

print(pets)

HERE,

  • pets = {...} creates a dictionary that contains pets
  • print(pets) prints the contents of our dictionary
  • pets.clear() calls the clear method of the dictionary object which removes all the items from the dictionary.
  • print(pets) prints the contents of our dictionary after it has been cleared. Executing the above code produces the following results
{'cats': 'Disliked', 'dogs': 'Liked', 'snakes': 'Loved'}
{} #empty dictionary is returned after clearing

How to get all the dictionary keys in python

The following code shows you how to return all of the keys from a dictionary.

pets = {
    'cats':'Disliked',
    'dogs':'Liked',
    'snakes':'Loved'
}

keys = pets.keys()

print(keys)

HERE,

  • keys = pets.keys() calls the keys method on the dictionary object that returns all the keys

Executing the above code produces the following results

dict_keys(['cats', 'dogs', 'snakes'])

How to get all the values from

The following code shows you how to get all the values from a dictionary

pets = {
    'cats':'Disliked',
    'dogs':'Liked',
    'snakes':'Loved'
}

values = pets.values()

print(values)

HERE,

  • values = pets.values() calls the value method on the pets dictionary

How to get a value using a dictionary key

The following code shows you how to get the value of a key.

pets = {
    'cats':'Disliked',
    'dogs':'Liked',
    'snakes':'Loved'
}

print(pets.get('snakes'))

HERE,

  • print(pets.get('snakes')) prints the value of the snake key

Executing the above results produces the following results

Loved

How to remove an item from a dictionary

The following code shows you how to remove an item by key from a dictionary

pets = {
    'cats':'Disliked',
    'dogs':'Liked',
    'snakes':'Loved'
}

pets.pop('cats')

print(pets)

HERE,

  • pets.pop('cats') removes the item with the key of cats

Executing the above code produces the following code

{'dogs': 'Liked', 'snakes': 'Loved'}

Summary

Dictionaries allow us to store items in a collection using a key and a value. Dictionaries are defined using curly brackets and they are mutable. This means you can modify them after you clear them. Dictionaries are objects so they come with built-in methods that allow us to do more without writing custom code.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...