Table of Contents


Just like lists, Python dictionaries (dict) are another mutable data structure. However, in contrast to lists and tuples, dictionaries are unordered. That is, the order of the elements is not important. Instead, each value has an associated key. We retrieve values by specifying the corresponding keys. Keys are unique within a dictionary while values may not be unique. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Defining a Dictionary

A Python dictionary is written as a sequence of comma-separated key:value pairs enclosed within a pair of curly braces {}. The following creates a dictionary of exam scores with the corresponding student names as keys.

EXAMPLE Defining a dictionary.

1scores = {"Carol":81, "Sammy":85, "Derrick":68, "Juan":72}
{'Carol': 81, 'Sammy': 85, 'Derrick': 68, 'Juan': 72}

The following example demonstrates that dictionaries are unordered, i.e. order of the elements is inconsequential.

EXAMPLE Dictionaries are unordered.

1table1 = {"Name": "Candice", "Age":22, "Gender": "Female", "Home": "NY"}
2table2 = {"Gender": "Female", "Name": "Candice", "Home": "NY", "Age":22}
3table1 == table2

We can access specific values of a dictionary using their corresponding keys. In the previous example of scores, the keys are the names of the students.

EXAMPLE Accessing the score (value) of a student using his name (key).


Dictionaries can have integer keys with string values:


1dict1 = {1: 'apple', 2: 'orange',3:'banana'}
{1: 'apple', 2: 'orange', 3: 'banana'}
Note: Dictionaries can have values of any data types or structures. But the keys cannot be repeated and need to be of an immutable type.

EXAMPLE keys cannot be repeated and must be immutable.

1dict2 = {'weather': 'thunderstorms', 1: [2, 4, 3], (20,30):92}
{'weather': 'thunderstorms', 1: [2, 4, 3], (20, 30): 92}

EXAMPLE Accessing a value using its key.

1dict2[(20,30)] # the key is a tuple

Modifying a Dictionary

Dictionaries are mutable. We can modify a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry.

EXAMPLE Updating the value of a dictionary.

1entry = {'name': 'Wendy', 'age': 26, 'gender':'female','height':173}
2entry['age']=27 #update an existing value
{'name': 'Wendy', 'age': 27, 'gender': 'female', 'height': 173}

EXAMPLE Adding an item to a dictionary.

1entry['country']= 'Canada' # add an additional item
{'name': 'Wendy',
 'age': 27,
 'gender': 'female',
 'height': 173,
 'country': 'Canada'}

We can remove a particular item in a dictionary using the del keyword.

EXAMPLE Remove an item from a dictionary.

1del entry['height']
{'name': 'Wendy', 'age': 27, 'gender': 'female', 'country': 'Canada'}

Or we can delete the entire dictionary using the del keyword.

EXAMPLE Delete entire dictionary.

1del entry

NameError                                 Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_24020/ in <module>
      1 del entry
----> 2 entry

NameError: name 'entry' is not defined

In the above example, an error is reported since the dictionary has been deleted.

List vs Tuple vs Dictionary

At this point, let us summarize the key properties of the three types of data structures we have learnt so far.

Data Structure Ordered Indexed Mutable Example
List ✔️ ✔️ ✔️ [1,2,3]
Tuple ✔️ ✔️ (1,2,3)
Dictionary ✔️ ✔️ {'a':1 , 'b':2, 'c':3}

Both lists and tuples are made up of ordered elements which are referenced using indices. The order of the elements is important. For example, [1,2,3] is not the same list as [3,1,2]. A dictionary is unordered since there is no inherent order for its elements. For example, {'a':1 , 'b':2, 'c':3} is the same dictionary as {'b':2 , 'a':1 , 'c':3}. All three data structures are indexed since elements can be referenced using indices for lists and tuples, and keys for dictionaries. Finally, all data structures are mutable except tubles. That is, both lists and dictionaries can be modified without creating a new object.


Dictionary Methods

We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the specified key and returns its value.

EXAMPLE Removes an item from a dictionary using pop().

1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
1dict1 # dictionary with above item removed
{1: 'apple', 3: 'banana', 4: 'pineapple'}

We will get an error if the specified key does not exist.

EXAMPLE Using pop() when key does not exist.


KeyError                                  Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_24020/ in <module>
----> 1 dict1.pop(8)

KeyError: 8

However, we can specify a default value to return if the specified key does not exist.

EXAMPLE Using pop() with default value (when key does not exist).

1dict1.pop(8,"no such key")
'no such key'

The popitem() method removes the last item from the dictionary. The method returns the removed item as a tuple.

EXAMPLE Using popitem() to remove last item.

1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
(4, 'pineapple')
1dict1 # updated
{1: 'apple', 2: 'orange', 3: 'banana'}

The clear() method removes all items from the dictionary.

EXAMPLE Using clear() to remove all items.


Since dictionaries are mutable, the copy() method is available to create an independent duplicate of an existing dictionary. In the following example, dict2 is created as a copy of dict1. dict1 then has its last item removed. But dict2 is not affected.

EXAMPLE Using copy() to create an independent copy.

1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict2 = dict1.copy()
{1: 'apple', 2: 'orange', 3: 'banana', 4: 'pineapple'}

If we had used the assignment dict2 = dict1, then dict2 will be affected as well.

EXAMPLE Using dict2() = dict1() to create a dependent copy.

1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict2 = dict1
{1: 'apple', 2: 'orange', 3: 'banana'}

The keys() method returns the keys of the dictionary as a view object.

EXAMPLE Get the keys of a dictionary.

1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
dict_keys([1, 2, 3, 4])

The values() method returns the values of the dictionary as a view object.

EXAMPLE Get the values of a dictionary.

dict_values(['apple', 'orange', 'banana', 'pineapple'])
Question: What are view objects?

These view objects are dynamic view objects, meaning that when the dictionary changes, the view reflects these changes. For example, the keys view object is not just a mere copy of the keys at a given point in time, but rather a window that shows you the keys exactly; if they are changed, then what you see through the window change as well.

Let’s take a look at the following example.

EXAMPLE What is a view object?

We first assign the view object of the values to a new variable.

1dictVals = dict1.values()
dict_values(['apple', 'orange', 'banana', 'pineapple'])

Now we modify the dictionary. The view object reflects the changes.

1dict1[2] = "kiwi"
dict_values(['apple', 'kiwi', 'banana', 'pineapple'])

To merge two dictionaries, we use the pipe | character.

EXAMPLE Merging dictionaries.

1scores1 = {"Carol":81, "Sammy":85, "Derrick":68, "Juan":72}
2scores2 = {"Wendy":79, "Tom":86}
3allScores = scores1 | scores2
{'Carol': 81, 'Sammy': 85, 'Derrick': 68, 'Juan': 72, 'Wendy': 79, 'Tom': 86}

The get() method returns the value corresponding to the specified key.

EXAMPLE Access a value with get() method.


The following returns nothing since the key does not exist.

EXAMPLE get() method when key does not exist.


There is no output above since the key does not exist. However, We can use an optional default value in this case.

EXAMPLE get() method with default value.

1allScores.get("Hamilton", "N/A")  # default value is "N/A"

The setdefault(key, optional default value) method returns the value of the specified key. If the key does not exist, a new item is created with the specified key and the specified default value.

EXAMPLE setdefault() method when key exists.

1allScores.setdefault("Tom",100) # this key exists, so the default value (100) is ignored.

EXAMPLE setdefault() method when key does not exist.

1allScores.setdefault("Lisa",100)  # this key does not exist, a new item with the default value is inserted.
{'Carol': 81,
 'Sammy': 85,
 'Derrick': 68,
 'Juan': 72,
 'Wendy': 79,
 'Tom': 86,
 'Lisa': 100}

If the default value is not provided, the new item’s value will be set to None.

EXAMPLE setdefault() method when key does not exist (& default value not specified).

{'Carol': 81,
 'Sammy': 85,
 'Derrick': 68,
 'Juan': 72,
 'Wendy': 79,
 'Tom': 86,
 'Lisa': 100,
 'Cod': None}

Let’s summarize all the dictionary methods we have learnt.

Method Description
clear() Removes all the elements from the dictionary.
copy() Returns a copy of the dictionary.
get() Returns the value of the specified key.
items() Returns a list containing a tuple for each key value pair.
values() Returns a list of all the values in the dictionary.
keys() Returns a list containing the dictionary’s keys.
pop() Removes the element with the specified key.
popitem() Removes the last inserted key-value pair.
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value.
update() Updates the dictionary with the specified key-value pairs.