Dictionaries are a way to store information that is connected in some way.
Dictionaries store information in key-value pairs
thus, one piece of dictionary is connected to at least another piece of information
dictionaries do not store information in a particular order
General syntax:
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 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
# Print out the items in the dictionary.
for class_school, task in dictionary_example.items():
print("\nClass: %s" % class_school)
print("Task: %s" % task)
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 6 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 line.
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:
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:
dictionary_example = {"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."}
dictionary_example
{'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'}
The way we do that is:
And here is the output:
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 harder, 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
Key: PL208
Value: I still have to prepare for the final exam.
Key: PL360
Value: I need to submit a final draft
Key: PL399
Value: Modified task
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 in a dictionary alphabetically.
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:
Let us say that we want to print Ever’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 make a dictionary of pets, with some 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
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.
print("Here is what I know about Willie:")
Here is what I know about Willie:
kind: dog
owner: eric
vaccinated: True
Notice how we extract information from that dictionary
Or
If we extract elements from the dictionary that do not exist, the code will produce an error.
We can obviously be more efficient about how we print the values in the dictionary.
We can print the values in the dictionary in the following way:
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("\nHere is what I know about %s:" % pet_name)
print("kind: " + pet_information['kind'])
print("owner: " + pet_information['owner'])
print("vaccinated: " + str(pet_information['vaccinated']))
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("\nHere is what I know about %s:" % 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:
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("\nHere is what I know about %s:" % 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
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("\nHere is what I know about %s:" % 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:
We can create a dictionary by doing:
Simone just changed her vaccination status: so she just got the vaccine.
How would you change that within the dictionary?
Simone just changed her vaccination status: so she just got the vaccine.
How would you change that within the dictionary?
How would you create a cumulative age given that the dogs are 1, 5 and 8 respectively?
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 useful, but it can get unwieldy quickly.
Other data structures such as classes or databases could be useful to store information.
Sets are unordered collection of elements of the same type, characterized by having 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
the parentheses ()
are used to define the tuple
set(...)
is a function that creates a set from the iterables passed to it.
Therefore the set can be written either as:
or
Other examples of sets are:
{('Python', 'Perl'), ('Paris', 'Berlin', 'London')}
The following will not work (will yield an error).
This is because lists are mutable objects. To get that to work, we would do:
Sets are particularly useful when we want to eliminate duplicates
The union of two sets contains all the elements from both sets, without duplicates.
set_a = {"apple", "banana", "cherry"}
set_b = {"cherry", "date", "elderberry"}
# Union of set_a and set_b
set_union = set_a.union(set_b)
set_union
{'apple', 'cherry', 'banana', 'elderberry', 'date'}
You can also use the |
operator for union:
The intersection of two sets contains only the elements that are present in both sets.
set_a = {"apple", "banana", "cherry"}
set_b = {"cherry", "date", "elderberry"}
# Intersection of set_a and set_b
set_intersection = set_a.intersection(set_b)
set_intersection
{'cherry'}
Alternatively, you can use the &
operator:
The difference of two sets contains the elements that are 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.
set_a = {"apple", "banana", "cherry"}
set_b = {"cherry", "date", "elderberry"}
# Symmetric difference of set_a and set_b
set_symmetric_difference = set_a.symmetric_difference(set_b)
set_symmetric_difference
{'banana', 'date', 'apple', 'elderberry'}
Popescu (JCU): Lecture 7