Python Lesson 9
Python Lesson 9
Python Dictionaries
Lesson 9 Content
• Python Dictionaries
• Dictionary
• Dictionary Items
• Ordered or Unordered?
• Changeable
• Duplicates Not Allowed
• Dictionary Length
• Dictionary Items - Data Types
• type()
• The dict() Constructor
• Python Collections (Arrays)
• Access Items
• Accessing Items
• Get Keys
• Get Values
• Get Items
• Check if Key Exists
• Change Items
• Change Values
• Update Dictionary
• Add Items
• Adding Items
• Update Dictionary
• Remove Items
• Loop Dictionaries
• Copy Dictionaries
• Nested Dictionaries
• Python - Dictionaries Methods
• Python - Dictionaries Exercises
Python Dictionaries
Dictionary Items
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that order
will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an
index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has
been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Python - Access Dictionary Items
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key: There is also a method called get() that will give you the
thisdict = { same result:
"brand": "Ford",
"model": "Mustang", Example
"year": 1964, Get the value of the "model" key:
"year": 2020 x = thisdict.get("model")
}
x = thisdict["model"]
The list of the keys is a view of the dictionary, The list of the values is a view of the dictionary,
meaning that any changes done to the meaning that any changes done to the dictionary
dictionary will be reflected in the keys list. will be reflected in the values list.
Example Example
Add a new item to the original dictionary, Make a change in the original dictionary, and
and see that the keys list gets updated as see that the values list gets updated as well:
well: car = {
car = { "brand": "Ford",
"model": "Mustang",
"brand": "Ford",
"year": 1964
"model": "Mustang", }
"year": 1964 x = car.values()
} print(x) #before the change
x = car.keys() car["year"] = 2020
print(x) #before the change print(x) #after the change
car["color"] = "white" Example
print(x) #after the change
Add a new item to the original dictionary, and
see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
x = thisdict.items()
The returned list is a view of the items of the dictionary, meaning that any changes done to the
dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Example
Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the item does
not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Python - Remove Dictionary Items
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Python - Loop Dictionaries
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods
to return the values as well.
Example Example
Print all key names in the dictionary, one by one: Print all values in the dictionary, one by one:
for x in thisdict: for x in thisdict:
print(x) print(thisdict[x])
Example
You can also use the values() method to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
Example
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
Python - Copy Dictionaries
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to
dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Python Dictionary Methods
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value