LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Lesson 26: Dictionaries In Python
A dictionary is a collection which is ordered, changeable and do not allow duplicates.Dictionaries are used to store data values in key:value pairs. In Python 3.6 and earlier, dictionaries are unordered. But as of Python version 3.7, dictionaries are ordered.
Dictionaries are written with curly brackets, and have keys and values.
Example Code: Create and print a dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items:
Dictionary items are presented in key:value pairs, and can be referred to by using the key name. Dictionary items are ordered, changeable, and does not allow duplicates. Example Code: Print the "brand" value of the dictionary.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021
}
print(thisdict["brand"])
output will be
Ford
What is meant by Ordered or Unordered?
When it is said 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 Code: Duplicate values will overwrite existing values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 2020,
"year": 2021
}
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'Mustang', 'year': 2021}
How to deterine the Dictionary Length?
We can determine how many items a dictionary has, by using the len() function.
Example Code: Print the number of items in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 2020,
"year": 2021
}
print(len(thisdict))
output will be
3
Data Types: The values in dictionary items can be of any data type.
Example Code: String, int, boolean, and list data types.
thisdict = {
"brand": "Ford",
"electric": False,
"year": 2021,
"colors": ["red", "white", "blue"]
}
print(thisdict)
output will be
{'brand': 'Ford', 'electric': False, 'year': 2021, 'colors': ['red', 'white', 'blue']}
type(): dictionaries are defined as objects with the data type 'dict' i.e.
Example Code: Print the data type of a dictionary.
thisdict = {
"brand": "Ford",
"electric": False,
"year": 2021,
"colors": ["red", "white", "blue"]
}
print(type(thisdict))
output will be
class 'dict'
How to Access Dictionary Items?
A dictionary items can be access by referring to its key name, inside square brackets.
Example Code 1: Get the value of the "model" key.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = thisdict["model"]
print(x)
output will be
F-150
A dictionary items can also be access by get() method.
Example Code 2: Get the value of the "model" key.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = thisdict.get("model")
print(x)
output will be
F-150
Get Keys
Example Code A: Get a list of the keys.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = thisdict.keys()
print(x)
output will be
dict_keys(['brand', 'model', 'year'])
Note: The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
Example Code B: Add a new item to the original dictionary, and also ensure that the keys list gets updated.
car = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = car.keys()
print(x) #before the change
car["color"] = "white" #Adding a new item
print(x) #after the change
output will be
dict_keys(['brand', 'model', 'year']) #This output is for before the change
dict_keys(['brand', 'model', 'year', 'color']) #This output is for after the change
Get Values
The values() method will return a list of all the values in the dictionary.
Example Code A: Get a list of the values.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = thisdict.values()
print(x)
output will be
dict_values(['Ford', 'F-150', 2021])
Note: The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Example Code B: Add a new item to the original dictionary, and also ensure that the values list gets updated.
car = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = car.values()
print(x) #before the change
car["color"] = "white" #Adding a new item
print(x) #after the change
output will be
dict_values(['Ford', 'F-150', 2021]) #This output is for before the change
dict_values(['Ford', 'F-150', 2021, 'white']) #This output is for after the change
Get Items: How to Get All Items of A Dictionary?
The items() method will return each item in a dictionary, as tuples in a list.
Example Code: Get a list of the key:value pairs.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = thisdict.items()
print(x)
output will be
dict_items([('brand', 'Ford'), ('model', 'F-150'), ('year', 2021)])
Note: 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 Code A: Make a change in the original dictionary, Add a new item to the original dictionary,
and also ensure that the values list gets updated.
car = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = car.items()
print(x) #before the change
car["year"] = 2022
print(x) #after the change
output will be
dict_items([('brand', 'Ford'), ('model', 'F-150'), ('year', 2021)]) #This output is for before the change
dict_items([('brand', 'Ford'), ('model', 'F-150'), ('year', 2022)]) #This output is for after the change
Example Code B: Add a new item to the original dictionary, and see that the items list gets updated as well
car = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
x = car.items()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
output will be
dict_items([('brand', 'Ford'), ('model', 'F-150'), ('year', 2021)]) #This output is for before the change
dict_items([('brand', 'Ford'), ('model', 'F-150'), ('year', 2021), ('color', 'red')]) #This output is for after the change
How to Check if Key Exists?
To determine if a specified key is present in a dictionary use the in keyword
Example: Check if "model" is present in the dictionary
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
output will be
Yes, 'model' is one of the keys in the thisdict dictionary
How to Change Dictionary Items?
Change Values: You can change the value of a specific item by referring to its key name.
Example Code: Change the "year" to 2022
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict["year"] = 2022
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2022}
How to Update Dictionary?
We can update the dictionary using update() method it will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example Code: Update the "year" of the car by using the update() method
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict.update({"year": 2022})
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2022}
Adding Items: How to Add Items to Dictionary?
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
Example Code:
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict["color"] = "red"
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2021, 'color': 'red'}
Update Dictionary: How to 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 Code: Add a color item to the dictionary by using the update() method.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict.update({"color": "white"})
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2021, 'color': 'white'}
Removing Items: How to Remove Dictionary Items?
There are several methods to remove items from a dictionary.
Example Code 1: The pop() method removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict.pop("model")
print(thisdict)
output will be
{'brand': 'Ford', 'year': 2021}
Example Code 2: The popitem() method removes the last inserted item.
Note: (in versions before 3.7, a random item is removed instead)
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict.popitem()
print(thisdict)
output will be
{'brand': 'Ford', 'model': 'F-150'}
Example Code 2: The del keyword removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
del thisdict["model"]
print(thisdict)
output will be
{'brand': 'Ford', 'year': 2021}
Example Code 3: The del keyword can also delete the dictionary completely.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
del thisdict
print(thisdict)
Note: This will cause an error because "thisdict" no longer exists.
Example Code 4: The clear() method empties the dictionary.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
thisdict.clear()
print(thisdict)
output will be
{}
Note: the dictionary will still exist but all items will be cleared and dictionary will be emptied.
Loop Dictionaries: How to 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.(Refer to Example5 Loop through both keys and values, by using the items() method)
Example Code 1: Print all key names in the dictionary, one by one.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
for x in thisdict:
print(x)
output will be
brand
model
year
Example2: Print all values in the dictionary, one by one.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
for x in thisdict:Ford
print(thisdict[x])output will be
F-150
2021
Example3: You can also use the values() method to return values of a dictionary.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
for x in thisdict.values():
print(x)
output will be
Ford
F-150
2021
Example4: You can use the keys() method to return the keys of a dictionary.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
for x in thisdict.keys():
print(x)
output will be
brand
model
year
Example5: Loop through both keys and values, by using the items() method.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
for x, y in thisdict.items():
print(x, y)
output will be
brand Ford
model F-150
year 2021
Copy Dictionaries: How to Copy a Dictionary?
1. Copy a Dictionary using the built-in Dictionary method copy()
Example Code: Make a copy of a dictionary with the copy() method
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
mydict = thisdict.copy()
print(mydict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2021}
2. Copy a Dictionary using the built-in function dict()
Example Code: Make a copy of a dictionary with the dict() function.
thisdict = {
"brand": "Ford",
"model": "F-150",
"year": 2021,
}
mydict = dict(thisdict)
print(mydict)
output will be
{'brand': 'Ford', 'model': 'F-150', 'year': 2021}
Nested Dictionaries: A dictionary can contain dictionaries, this is called nested dictionaries.
Example Code 1: Create a dictionary that contain three dictionaries.
Basketball_Hall_of_Famers = {
"player1" : {
"name" : "Oscar Robertson ",
"year inducted" : 1980
},
"player2" : {
"name" : "Dave Cowens",
"year inducted" : 1991
},
"player3" : {
"name" : "Bob Lanier",
"year inducted" : 1992
}
}
print(Basketball_Hall_of_Famers)
output will be
{'player1': {'name': 'Oscar Robertson ', 'year inducted': 1980}, 'player2': {'name': 'Dave Cowens', 'year inducted': 1991}, 'player3': {'name': 'Bob Lanier', 'year inducted': 1992}}
Example2: Add three dictionaries into a new dictionary.
Create three dictionaries, then create one dictionary that will contain the other three dictionaries
output will be
{'player1': {'name': 'Oscar Robertson ', 'year inducted': 1980}, 'player2': {'name': 'Dave Cowens', 'year inducted': 1991}}
{'player1': {'name': 'Oscar Robertson ', 'year inducted': 1980}, 'player2': {'name': 'Dave Cowens', 'year inducted': 1991}}