Write Cool Programs Using Python Dictionary.

In this Python dictionary tutorial, you will learn how to use dictionary methods to write some cool programs such as a phone book program.

Also, you will get the source code of all the programs in this tutorial.

Please note,

This tutorial is for Python version 3.x.

Let’s get to business now.

What is a dictionary in Python?

Python dictionary associates a collection of keys with data values.

Unlike list in Python, a dictionary organizes information by association, not position.

That’s to say that, the key-value pairs are arranged in no particular order.

The key-value pairs in a dictionary are separated by a comma.

A colon (:) separates a key and its associated value.

I would love to refer these key-value pairs as entries.

The key-value pairs or entries are enclosed in curly braces ({ }).

Python dictionary example

In a  new file editor window,  type the following code snippet and save it as Dictionary_example.py

Running Dictionary_example.py you will get:

Note the following:

  • The keys in a dictionary can be any immutable Python data type(tuple)
  • Python dictionary keys can be strings or integers.
  • The associated value can be any Python data type.

 

In a  new file editor window,  type the following code snippet and save it as Dictionary_example2.py

Running Dictionary_example2.py you will get:

Python will raise a TypeError error if your keys are in list form.

Take a look:

How to know the number of entries in a Python dictionary.

Python has a built-in function for this operation.

The len() can be used to know the number of entries in a Python dictionary.

Observe the following code snippet. You can type them in Python’s interactive shell.

Adding keys to an existing Python Dictionary

You add a new key/value pair to a dictionary by using the subscript operator [].

Here’s the format:

“The variable name of your dictionary”[“key ”]=”Value”

Remember, that is just a format.

You use quotes appropriately.

The next code snippet creates an empty dictionary and adds three new entries:

(Please type them in Python’s interactive shell.)

Can you do one for me following these instructions?

  • Create an empty dictionary and assign it to a variable.
  • Let that variable be student_info
  • Add the following entries (key-value pair).
  1. name-Oscar”
  2. dept-computer science
  3. level-300

Now use a print statement to print your dictionary.

If you had problem on the way, don’t worry,

You are in a process, all you need is practice.

Here’s is our program    student_details.py

Running student_details.py, we will have:

Replacing  the values of an existing Python dictionary

Now, we have a program containing the details of Oscar.

What if Oscar is now in 400 level?

What can we do?

We can change the value associated with a particular key in a dictionary by using a subscript operator [].

Let’s change Oscar’s level with the code snippet below:

(Please type them in Python’s interactive shell.)

Accessing the values of a Python Dictionary.

Imagine a program, with numerous entries (key/value pairs) and we need just one value associated with a key.

We can print the whole dictionary using the print statement but that will be more work for us to look for that particular entry we need.

To save us time we can use the subscript operator [] to have access to values in a dictionary.

Here’s   an illustration:

(Please type them in Python’s interactive shell.)

Note: If a key is not in the dictionary, Python raises a  KeyError. You can observe that in the last print statement in the code snippet above.

Project 1:

Write a Python program to prompt the user to enter the position of a chemical element and output the element. Your program should cover the first 20 elements.

The first 20 elements are:

Hydrogen, Helium, Lithium, Beryllium, Boron, Carbon, Nitrogen, Oxygen, Fluorine, Neon, Sodium, Magnesium, Aluminum, Silicon, Phosphorus, Sulphur, Chlorine, Argon, Potassium,  Calcium.

Save the program as elements.py

If you didn’t succeed in project 1, don’t worry practice makes perfect.

Running elements.py you will get:

I inputted 6, 9 and 19 and the program outputs were Carbon,  Fluorine, and Potassium respectively.

Removing Entries in Python Dictionary.

Let’s say we have a dictionary containing the names and numbers of some people and we don’t want their contacts anymore.

To do so you have to use a del statement with a subscript operator [].

Observe the following code snippets:

(Please type them in Python’s interactive shell.)

Using D.pop() :

The pop() method can be used to remove entries in a Python dictionary. The key has to be in the dictionary. This method removes the key that’s present in the dictionary and returns the value of the associated key.

(Please type them in Python’s interactive shell.)

Note: If the key is not present in the dictionary, Python will raise a KeyError.

To avoid error in our program, you do the following:

(Please type them in Python’s interactive shell.)

The None argument prevents a KeyError when the key is not present in the dictionary. So advice you use it.

for loop with Python Dictionary.

A for loop is used to print the keys or values or both in a Python dictionary.

Let’s play with Python dictionary using for loop.

(Please type them in Python’s interactive shell.)

Python dictionary methods and their functions

We have used some dictionary methods before.

I will run through them and include more dictionary methods.

Python dictionary methods and their functions

Python Dictionary Methods

The pop() method

Dict.pop(key, [default]):

The operation removes the specified key and returns the corresponding value. If the key is not present in the dictionary, the default is returned.

Note:    

If the default is omitted and the specified key is not present, Python will raise a KeyError

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The value() method

list(dict.value()):

This Python dictionary method returns a list of the values in a dictionary.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The items() method

list(dict.items()):

This Python dictionary method returns a list of tuples containing the entries of the dictionary.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The clear() method

Dict.clear():

This Python Dictionary method removes all the entries in a dictionary.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The keys() method

Dict.keys():

This Python dictionary method returns a list of the keys in a dictionary.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The copy() method

Dict.copy():

This Python dictionary method does a shallow copy of a dictionary.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The get method

Dict.get(key,[default] ):

This Python dictionary method returns the value of the specified key. If the key is not present, a default value is returned.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

The setdefault() method:

Dict.setdefault(key[,value]):

Apart from using a subscript operator [] to add a new entry to a Python dictionary, a setdefault() method can be used to add a new entry.

But there’s a twist to this method.

Here’s the twist.

Two arguments are passed to this method. The first argument checks if the key exists, if it does not exist the second argument passed is the value assigned to the key. This value is returned.

But if the first argument exists in the dictionary, the original value is returned and the second argument is ignored.

Please observe the following code snippets.

(Please type them in Python’s interactive shell.)

Checking if a key or value exists in a Python dictionary.

The in operator can be used to check if a key or value exists in a Python dictionary.

If the key or value is in the dictionary, a True value is returned. If the key or value is not present, a False value is returned.

If you use a not in operator if the key or value is present a False value is returned and vice versa.

Observe the following code snippet:

(Please type them in Python’s interactive shell.)

We have done much, I think we should take a break and write a program.

Project 2:

Write a program to store your love ones phone number using the concept of Python dictionary.

If you cannot do it, here is the source code. Please study it carefully.

Save this program as phonebook.py

Running phonebook.py will look like:

Am sure by now you can write your phone book program. I want you to upgrade it by providing features to removing a contact, replacing a contact’s number.

We have come to the end of this tutorial.

 

Tell your friends on Twitter on your new achievement in Python. They will love to hear it.Trust me. 'Winks' Click To Tweet

Please check out this great Python book:

Computer Science; Software Engineering/Programming and Operating Systems

If you’re having a problem with Python dictionary, feel free to comment.

Sharing is bliss!!!…

About the author

Rapture Godson

I am Godson; the brain behind Cool Python Codes. On this blog, I will make Python much fun and very practical. My up-to-date tutorials are based on my studies and they are very easy for you to understand.

6 Comments

Leave a Comment