L7: Dictionaries and Sets

Bogdan G. Popescu

John Cabot University

Dictionaries

Introduction

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

General syntax:

Python
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

Keys must be unique, but values do not need to be.

Dictionaries

Introduction

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:

Python
dictionary_name = {key_1: value_1,
                   key_2: value_2,
                   key_3: value_3,
                   }

This is easier to read when values are long.

Dictionaries

Example

An example of the dictionary is the following:

Python
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."}

Dictionaries

Extracting elements from a dictionary

We can get individual items out of the dictionary by giving the dictionary’s name and the key in square brackets:

Python
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."}
Python
print("Class: PL208")
print(f"Tasks left: {dictionary_example['PL208']}")
print("Class: PL360")
print(f"Tasks left: {dictionary_example['PL360']}")
print("Class: PL366")
print(f"Tasks left: {dictionary_example['PL366']}")
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.

Dictionaries

Extracting elements from a dictionary

The code looks repetitive.

Dictionaries have their own for-loop syntax.

The dictionary can be better presented in the following way.

Python
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."}
Python
# Print out the items in the dictionary.
for class_school, task in dictionary_example.items():
    print(f"Class: {class_school}")
    print(f"Task: {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.

Dictionaries

Extracting elements from a dictionary

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.

Dictionaries

Exercise

Task 1: Create a dictionary - students_grades where you have the following students and their corresponding grades:

  • Alice: 85
  • Bob: 90
  • Charlie: 78

Task 2: Print every student and their grade using a for loop

Task 3: Update the grade for “Alice” to 88.

Dictionaries

Exercise

Task 1:

Python
students_grades = {"Alice": 85, "Bob": 90, "Charlie": 78}

Task 2:

Python
for student, grade in students_grades.items():
  print(student, grade)
Alice 85
Bob 90
Charlie 78

Task 3:

Python
students_grades["Alice"]=88
students_grades
{'Alice': 88, 'Bob': 90, 'Charlie': 78}

Dictionaries

Operations with Dictionaries

There are a variety of operations one can do with dictionaries.

Some common operations include:

  • Adding new key-value pairs
  • Modifying values in a dictionary
  • Removing key-value pairs

Dictionaries

Operation 1: Adding a new key-value pair

We can easily add a new key-value pair to our dictionary:

Python
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.'}
Python
dictionary_example["PL999"]="Nothing left"
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.', 'PL999': 'Nothing left'}

Dictionaries

Operation 2: Removing key-value pairs

Let us say that we want to remove the newly added pair.

Python
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.', 'PL999': 'Nothing left'}

The way we do that is:

Python
del dictionary_example['PL999']

Here is the output:

Python
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.'}

Dictionaries

Operation 3: Modifying values in a dictionary

We have already seen that modifying values in a dictionary is straightforward.

Python
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.'}
Python
dictionary_example['PL366'] = "Modified task"
dictionary_example
{'PL208': 'I still have to prepare for the final exam.', 'PL360': 'I need to submit a final draft', 'PL366': 'Modified task'}

Dictionaries

Operation 4: Modifying keys in a dictionary

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:

  • copying the value to the new key
  • removing the old key-value pair
Python
#Step1: Copying the value to the new key 
dictionary_example['PL399'] = dictionary_example['PL366']
#Step2: Deleting the old value
del dictionary_example['PL366']
Python
#Step3: Checking the result
dictionary_example
{'PL208': 'I still have to prepare for the final exam.', 'PL360': 'I need to submit a final draft', 'PL399': 'Modified task'}

Dictionaries

Looping through all the key-value pairs

This is how we can loop through all the items of a dictionary.

Python
for key, value in dictionary_example.items():
    print(f'Key: {key}')
    print(f'Value: {value}')
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:

Python
print(dictionary_example.items())
dict_items([('PL208', 'I still have to prepare for the final exam.'), ('PL360', 'I need to submit a final draft'), ('PL399', 'Modified task')])

Dictionaries

Looping through all the key-value pairs

We can obtain only the keys from a dictionary in the following way:

Python
print(dictionary_example.keys())
dict_keys(['PL208', 'PL360', 'PL399'])

We can obtain only the values from a dictionary in the following way:

Python
print(dictionary_example.values())
dict_values(['I still have to prepare for the final exam.', 'I need to submit a final draft', 'Modified task'])

Dictionaries

Sorting keys

We can sort the keys alphabetically in a dictionary.

Python
print(sorted(dictionary_example.keys()))
['PL208', 'PL360', 'PL399']

Dictionaries

Nesting

Nesting is a powerful concept when using dictionaries.

It entails putting a list of dictionaries inside another list or dictionary.

Python
# This program stores and displays people's favorite numbers.
favorite_numbers = {'eric': [3, 11, 19, 23, 42],
                    'ever': [2, 4, 5],
                    'willie': [5, 35, 120]}

Dictionaries

Nesting

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:

Python
print(favorite_numbers['eric'])
[3, 11, 19, 23, 42]

Let us say that we want to print Ever’s favorite numbers:

Python
print(favorite_numbers['ever'])
[2, 4, 5]

Dictionaries

Dictionaries in a dictionary

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.

Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
        'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
        'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}

Dictionaries

Dictionaries in a dictionary

The way we can access information about the owners is the following:

Python
# Let's show all the information for each pet.
print("Here is what I know about Willie:")
print("kind: " + pets['willie']['kind'])
print("owner: " + pets['willie']['owner'])
print("vaccinated: " + str(pets['willie']['vaccinated']))
Here is what I know about Willie:
kind: dog
owner: eric
vaccinated: True

Dictionaries

Dictionaries in a dictionary

Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
        'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
        'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}
Python
# Let's show all the information for each pet.
print("Here is what I know about Willie:")
print("kind: " + pets['willie']['kind'])
print("owner: " + pets['willie']['owner'])
print("vaccinated: " + str(pets['willie']['vaccinated']))
Here is what I know about Willie:
kind: dog
owner: eric
vaccinated: True

Dictionaries

Dictionaries in a dictionary

Python
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
        'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
        'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True}}

Notice how we extract information from that dictionary

Python
pets['willie']['kind']
pets['walter']['kind']
'dog'
'cockroach'

Or

Python
pets['willie']['kind']
pets['willie']['owner']
'dog'
'eric'

The code will produce an error if we extract elements from the dictionary that do not exist.

Dictionaries

Dictionaries in a dictionary

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']))

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Dictionaries in a dictionary

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]))
  • The first loop gives us all the keys in the main dictionary, consisting of each pet’s name.
  • Each of these names can be used to ‘unlock’ the dictionary of each pet.

Dictionaries

Dictionaries in a dictionary

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]))
  • The inner loop goes through the dictionary for that individual pet and pulls out all of the keys in that individual pet’s dictionary.
  • We print the key, which tells us the kind of information we are about to see and the value of that key.

Dictionaries

Creating dictionaries through a loop

We can create dictionaries using a loop:

Python
names_dogs = ["Bowie", "Simone", "Marbs"]
breeds = ["Mixed", "Labrador", "Boston Terrier"]
owners = ["James", "James", "Andrea"]
vaccined_list = [True, False, True]

We can create a dictionary by doing the following:

Python
dict_dogs = {}
for name, breed, owner, vaccined in zip(names_dogs, breeds, owners, vaccined_list):
    dict_dogs[name] = {}
    dict_dogs[name]["breed"] = breed
    dict_dogs[name]["owner"] = owner
    dict_dogs[name]["vaccined"] = vaccined

Dictionaries

Exercise 1

Simone just changed her vaccination status, so she got the vaccine.

How would you change that within the dictionary?

Dictionaries

Exercise 1 Solution

Simone just changed her vaccination status, so she got the vaccine.

How would you change that within the dictionary?

Python
#How would you change the value if Simone got the vaccine?
dict_dogs['Simone']["vaccined"]=True
dict_dogs

Dictionaries

Exercise 2

Given that the dogs are 1, 5, and 8, how would you create a cumulative age?

Dictionaries

Exercise 2 Solution

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:

Python
ages = [1, 5, 8]
for name, age in zip(names_dogs, ages):
    dict_dogs[name]["ages"] = age
dict_dogs

Dictionaries

Exercise 2 Solution

The next step is to add these ages.

Python
sum(dog['ages'] for dog in dict_dogs.values())

Note:

  • dogs.values() - lists all the values in the dictionary
  • for dog in dogs.values(): is a generator expression
  • each dog is a dictionary corresponding to an individual dog’s details.

Dictionaries

Dictionaries in a dictionary

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

Introduction

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:

Python
cities =  {'Madrid', 'Barcelona', 'Atlanta'}
cities
{'Madrid', 'Atlanta', 'Barcelona'}

Sets

Introduction

Examples of sets:

Python
cities = set(["Paris", "Lyon", "London", "Berlin"])
cities
{'Berlin', 'Paris', 'Lyon', 'London'}
Python
cities = set(("Paris", "Lyon", "London", "Berlin"))
cities
{'Berlin', 'Paris', 'Lyon', 'London'}

Sets

Sets Example

A set() can take any iterable (e.g., list, tuple, string) to form a set.

Python
cities = set(("Paris", "Lyon", "London", "Berlin"))
cities
{'Berlin', 'Paris', 'Lyon', 'London'}
  • ("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.

Sets

Sets Example

Therefore, the set can be written either as:

Python
cities = set(("Paris", "Lyon", "London","Berlin"))
cities
{'Berlin', 'Paris', 'Lyon', 'London'}

or

Python
cities = {"Paris", "Lyon", "London","Berlin"}
cities
{'Berlin', 'Paris', 'Lyon', 'London'}

Sets

Sets Example

Other examples of sets are:

Python
cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
cities
{('Python', 'Perl'), ('Paris', 'Berlin', 'London')}

The following will not work (will yield an error).

Python
cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
cities

This is because lists are mutable objects. To get that to work, we would do:

Python
cities = set((tuple(["Python", "Perl"]), tuple(["Paris", "Berlin", "London"])))
cities
{('Python', 'Perl'), ('Paris', 'Berlin', 'London')}

Sets

Uses

Sets are handy when we want to eliminate duplicates.

Python
fruits = {'apple', 'orange', 'apple', 'pear'}
set(fruits) 
{'apple', 'orange', 'pear'}

Sets

Operations with Sets

Python
a = set('abcc')
b = set('cde')
  • Difference: letters in a but not in b
Python
a - b
{'b', 'a'}
  • Union: letters in a or b
Python
a | b
{'b', 'e', 'd', 'a', 'c'}
  • Intersection: letters in a and in b
Python
a & b 
{'c'}

Sets

Union

The union of two sets contains all the elements from both sets without duplicates.

Python
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
{'elderberry', 'apple', 'date', 'banana', 'cherry'}

You can also use the | operator for union:

Python
set_union_operator = set_a | set_b
set_union_operator
{'elderberry', 'apple', 'date', 'banana', 'cherry'}

Sets

Intersection

The intersection of two sets contains only the elements present in both sets.

Python
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:

Python
set_intersection_operator = set_a & set_b
set_intersection_operator
{'cherry'}

Sets

Difference

The difference between the two sets contains elements in the first set but not in the second.

Python
set_a = {"apple", "banana", "cherry"}
set_b = {"cherry", "date", "elderberry"}

# Difference of set_a and set_b
set_difference = set_a.difference(set_b)
set_difference
{'banana', 'apple'}
Python
set_difference_operator = set_a - set_b
set_difference_operator
{'banana', 'apple'}

Sets

Symmetric Difference

The symmetric difference contains elements that are in either of the sets but not in both.

Python
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
{'elderberry', 'banana', 'apple', 'date'}

Conclusion

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.