Dictionaries are a way to store information that is connected in some way.
Dictionaries store information in key-value pairs.
thus, one piece of the dictionary is connected to at least another piece of information
dictionaries do not store information in a particular order
Keys must be unique, but values do not need to be.
Since the keys and values in dictionaries can be long
Thus, we often write just one key-value pair on a line.
You might see dictionaries that look more like this:
This is easier to read when values are long.
An example of the dictionary is the following:
We can get individual items out of the dictionary by giving the dictionary’s name and the key in square brackets:
Class: PL208
Tasks left: I still have to prepare for the final exam.
Class: PL360
Tasks left: I need to submit a final draft
Class: PL366
Tasks left: I can relax. I have submitted everything necessary.
The code looks repetitive.
Dictionaries have their own for-loop syntax.
The dictionary can be better presented in the following way.
Python
Class: PL208
Task: I still have to prepare for the final exam.
Class: PL360
Task: I need to submit a final draft
Class: PL366
Task: I can relax. I have submitted everything necessary.
Thus, instead of using six lines, we used only 3.
This is much more efficient. Imagine if we had more classes…
It would be very inefficient to try to type all those lines.
Task 1: Create a dictionary - students_grades
where you have the following students and their corresponding grades:
Task 2: Print every student and their grade using a for
loop
Task 3: Update the grade for “Alice” to 88.
Task 1:
Task 2:
Alice 85
Bob 90
Charlie 78
Task 3:
There are a variety of operations one can do with dictionaries.
Some common operations include:
We can easily add a new key-value pair to our dictionary:
Python
{'PL208': 'I still have to prepare for the final exam.', 'PL360': 'I need to submit a final draft', 'PL366': 'I can relax. I have submitted everything necessary.'}
Let us say that we want to remove the newly added pair.
{'PL208': 'I still have to prepare for the final exam.', 'PL360': 'I need to submit a final draft', 'PL366': 'I can relax. I have submitted everything necessary.', 'PL999': 'Nothing left'}
We have already seen that modifying values in a dictionary is straightforward.
{'PL208': 'I still have to prepare for the final exam.', 'PL360': 'I need to submit a final draft', 'PL366': 'I can relax. I have submitted everything necessary.'}
Modifying a key is a little more complicated because each key is used to unlock a value.
The easiest way to do this is by:
This is how we can loop through all the items of a dictionary.
The .items()
method pulls all key-value pairs from a dictionary into a list of tuples:
We can obtain only the keys from a dictionary in the following way:
We can obtain only the values from a dictionary in the following way:
We can sort the keys alphabetically in a dictionary.
Nesting is a powerful concept when using dictionaries.
It entails putting a list of dictionaries inside another list or dictionary.
Nesting is a powerful concept when using dictionaries.
It entails putting a list of dictionaries inside another list or dictionary.
Let us say that we want to print Eric’s favorite numbers:
Another helpful fact about dictionaries is that we can have dictionaries inside dictionaries.
To demonstrate how and why this is useful, let’s create a dictionary of pets with information about each pet.
The way we can access information about the owners is the following:
Here is what I know about Willie:
kind: dog
owner: eric
vaccinated: True
Here is what I know about Willie:
kind: dog
owner: eric
vaccinated: True
Notice how we extract information from that dictionary
The code will produce an error if we extract elements from the dictionary that do not exist.
We can be more efficient in printing the values in the dictionary.
We can print the values in the dictionary in the following way:
Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
# Let's show all the information for each pet.
for pet_name, pet_information in pets.items():
print(f"Here is what I know about: {pet_name}")
print("kind: " + pet_information['kind'])
print("owner: " + pet_information['owner'])
print("vaccinated: " + str(pet_information['vaccinated']))
Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
# Let's show all the information for each pet.
for pet_name, pet_information in pets.items():
print(f"Here is what I know about: {pet_name}")
print("kind: " + pet_information['kind'])
print("owner: " + pet_information['owner'])
print("vaccinated: " + str(pet_information['vaccinated']))
Here is what I know about: willie
kind: dog
owner: eric
vaccinated: True
Here is what I know about: walter
kind: cockroach
owner: eric
vaccinated: False
Here is what I know about: peso
kind: dog
owner: chloe
vaccinated: True
Another way to print information from the dictionary is the following:
Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
# Let's show all the information for each pet.
for pet_name, pet_information in pets.items():
print(f"Here is what I know about: {pet_name}")
# Each animal's dictionary is in 'information'
for key in pet_information:
print(key + ": " + str(pet_information[key]))
Here is what I know about: willie
kind: dog
owner: eric
vaccinated: True
Here is what I know about: walter
kind: cockroach
owner: eric
vaccinated: False
Here is what I know about: peso
kind: dog
owner: chloe
vaccinated: True
Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
# Let's show all the information for each pet.
for pet_name, pet_information in pets.items():
print(f"Here is what I know about: {pet_name}")
# Each animal's dictionary is in 'information'
for key in pet_information:
print(key + ": " + str(pet_information[key]))
Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
# Let's show all the information for each pet.
for pet_name, pet_information in pets.items():
print(f"Here is what I know about: {pet_name}")
# Each animal's dictionary is in 'information'
for key in pet_information:
print(key + ": " + str(pet_information[key]))
We can create dictionaries using a loop:
Simone just changed her vaccination status, so she got the vaccine.
How would you change that within the dictionary?
Simone just changed her vaccination status, so she got the vaccine.
How would you change that within the dictionary?
Given that the dogs are 1, 5, and 8, how would you create a cumulative age?
The first thing to notice is that we need to add the list of ages to the dictionary.
We can do this in the following way:
The next step is to add these ages.
Note:
dogs.values()
- lists all the values in the dictionaryfor dog in dogs.values():
is a generator expressiondog
is a dictionary corresponding to an individual dog’s details.Dictionaries within dictionaries can be helpful, but it can get unwieldy quickly.
Other data structures, such as classes or databases, could be helpful to store information.
Sets are unordered collections of elements of the same type with no duplicate elements.
Sets support mathematical operations such as union, intersection, difference,
Sets are created with the set()
function.
Examples of sets:
A set()
can take any iterable (e.g., list, tuple, string) to form a set.
("Paris", "Lyon", "London" ,"Berlin")
is a tuple with four elements()
are used to define the tupleset(...)
is a function that creates a set from the iterables passed to it.Therefore, the set can be written either as:
{'Berlin', 'Paris', 'Lyon', 'London'}
Other examples of sets are:
The following will not work (will yield an error).
Sets are handy when we want to eliminate duplicates.
The union of two sets contains all the elements from both sets without duplicates.
The intersection of two sets contains only the elements present in both sets.
The difference between the two sets contains elements in the first set but not in the second.
The symmetric difference contains elements that are in either of the sets but not in both.
Dictionaries store key-value pairs, allowing efficient data organization, retrieval, and modification for tasks like storing student grades or managing tasks.
Nested dictionaries enable complex data structures, which are helpful for hierarchical or detailed data like pet information or student profiles.
Sets are unordered collections that automatically eliminate duplicates. They are helpful for operations like union, intersection, and difference.
Both dictionaries and sets offer versatile tools for data handling, enhancing readability, efficiency, and scalability in Python programs.
Popescu (JCU): Lecture 7