Dictionaries

A dictionary is an object that stores a collection of data. Each element has two parts - a key and an index. You use the key to locate a specific value. We call this key-value pairs.

Syntax and Methods

We create a dictionary by enclosing the elements inside of a set of curly braces { }.

We retrieve a value from a dictionary:

dictionary_name[key]

And not in Operators

We use the in and not in operators to test for a value in a dictionary.

Adding Elements to a Dictionary

dictionary_name[key] = value

Deleting Elements in a Dictionary

del dictionary_name[key]

len Function

You can use the function len to get the number of elements in a dictionary.

Creating an Empty Dictionary

You might want to create an empty dictionary where you then add elements to it as the program executes.

Using the for Loop

for var in dictionary:
    statement
    statement
    etc.

Dictionary Methods

Method Explanation

clear()

clears the contents of the dictionary

get()

gets the value associated with a specified key

items()

returns all the keys in a dictionary and their associated values as a sequence of tuples

keys()

returns all the keys in a dictionary as a sequence of tuples

pop()

returns the value associated with a specified key and removes that key-value pair from the dictionary

popitem()

returns a randomly selected key-value pair as a tuple from the dictionary and removes that key-value pair from the dictionary

values()

returns all the values in the dictionary as a sequence of tuples

Exercises

info

Note the >>> prompt in the examples below indicates that they are running in the PYTHON shell using the "interactive" mode.

dict types can be thought of a list of key:value pairs.

>>> marks = {'Rahul' : 86, 'Ravi' : 92, 'Rohit' : 75}
>>> marks
{'Rahul': 86, 'Ravi': 92, 'Rohit': 75}

>>> fav_books = {}
>>> fav_books['fantasy'] = 'Harry Potter'
>>> fav_books['detective'] = 'Sherlock Holmes'
>>> fav_books['thriller'] = 'The Da Vinci Code'
>>> fav_books
{'fantasy': 'Harry Potter', 'detective': 'Sherlock Holmes', 'thriller': 'The Da Vinci Code'}

>>> marks.keys()
dict_keys(['Rahul', 'Ravi', 'Rohit'])

>>> fav_books.values()
dict_values(['Harry Potter', 'Sherlock Holmes', 'The Da Vinci Code'])

Looping and printing.

>>> for book in fav_books.values():
                  print(book)

Harry Potter
Sherlock Holmes
The Da Vinci Code

>>> for name, mark in marks.items():
                  print(name, mark, sep=': ')

Ravi: 92
Rohit: 75
Rahul: 86

Modifying dicts and example operations.

>>> marks
{'Ravi': 92, 'Rohit': 75, 'Rahul': 86}
>>> marks['Rajan'] = 79
>>> marks
{'Ravi': 92, 'Rohit': 75, 'Rahul': 86, 'Rajan': 79}

>>> del marks['Ravi']
>>> marks
{'Rohit': 75, 'Rahul': 86, 'Rajan': 79}

>>> len(marks)
3

>>> fav_books
{'thriller': 'The Da Vinci Code', 'fantasy': 'Harry Potter', 'detective': 'Sherlock Holmes'}
>>> "fantasy" in fav_books
True
>>> "satire" in fav_books
False

Further Reading