Table of Contents
- Introduction
- Defining a Dictionary
- Modifying a Dictionary
- List vs Tuple vs Dictionary
- Dictionary Methods
Introduction
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}
2scores
{'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
True
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).1scores["Juan"]
72
Example
Dictionaries can have integer keys with string values.1dict1 = {1: 'apple', 2: 'orange',3:'banana'}
2dict1
{1: 'apple', 2: 'orange', 3: 'banana'}
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}
2dict2
{'weather': 'thunderstorms', 1: [2, 4, 3], (20, 30): 92}
Example
Accessing a value using its key.1dict2[(20,30)] # the key is a tuple
92
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
3entry
{'name': 'Wendy', 'age': 27, 'gender': 'female', 'height': 173}
Example
Adding an item to a dictionary.1entry['country']= 'Canada' # add an additional item
2entry
{'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']
2entry
{'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
2entry
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24020/597969434.py 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.
ADVERTISEMENT
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 usingpop()
.
1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict1.pop(2)
'orange'
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
Usingpop()
when key does not exist.
1dict1.pop(8)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24020/2520149429.py 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
Usingpop()
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
Usingpopitem()
to remove last item.
1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict1.popitem()
(4, 'pineapple')
1dict1 # updated
{1: 'apple', 2: 'orange', 3: 'banana'}
The clear()
method removes all items from the dictionary.
Example
Usingclear()
to remove all items.
1dict1.clear()
2dict1
{}
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
Usingcopy()
to create an independent copy.
1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict2 = dict1.copy()
3dict1.popitem()
4dict2
{1: 'apple', 2: 'orange', 3: 'banana', 4: 'pineapple'}
If we had used the assignment dict2 = dict1
, then dict2
will be affected as well.
Example
Usingdict2() = dict1()
to create a dependent copy.
1dict1 = {1: 'apple', 2: 'orange',3:'banana',4:'pineapple'}
2dict2 = dict1
3dict1.popitem()
4dict2
{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'}
2dict1.keys()
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.1dict1.values()
dict_values(['apple', 'orange', 'banana', 'pineapple'])
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 aview
object?
We first assign the view
object of the values to a new variable.
1dictVals = dict1.values()
2dictVals
dict_values(['apple', 'orange', 'banana', 'pineapple'])
Now we modify the dictionary. The view
object reflects the changes.
1dict1[2] = "kiwi"
2dictVals
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
4print(allScores)
{'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 withget()
method.
1allScores.get("Tom")
86
The following returns nothing since the key does not exist.
Example
get()
method when key does not exist.
1allScores.get("Hamilton")
There is no output above since the key does not exist. However, We can use an optional default value in this case.
ADVERTISEMENT
Example
get()
method with default value.
1allScores.get("Hamilton", "N/A") # default value is "N/A"
'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.
86
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.
2allScores
{'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).
1allScores.setdefault("Cod")
2allScores
{'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. |