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 dictionary is connected to at least another piece of information

  • dictionaries do not store information in a particular order

General syntax:

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:

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 dictionary is the following:

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:

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."}
print("\nClass: %s" % 'PL208')
print("Tasks left: %s" % dictionary_example['PL208'])
print("\nClass: %s" % 'PL360')
print("Tasks left: %s" % dictionary_example['PL360'])
print("\nClass: %s" % 'PL366')
print("Tasks left: %s" % 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

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

Dictionaries

Extracting elements from a dictionary

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.

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:

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

Task 2:

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

Task 3:

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:

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

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:

del dictionary_example['PL999']

And here is the output:

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.

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['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 harder, because each key is used to unlock a value.

The easiest way to do this is by:

  • copying the value to the new key
  • deleting the old value
#Step1: Copying the value to the new key 
dictionary_example['PL399'] = dictionary_example['PL366']
#Step2: Deleting the old value
del dictionary_example['PL366']
#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

for key, value in dictionary_example.items():
    print('\nKey: %s' % key)
    print('Value: %s' % 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:

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:

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

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

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 in a dictionary alphabetically.

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.

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

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

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

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

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 make a dictionary of pets, with some information about each pet.

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:

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

Dictionaries

Dictionaries in a dictionary

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:
print("kind: " + pets['willie']['kind'])
kind: dog
print("owner: " + pets['willie']['owner'])
owner: eric
print("vaccinated: " + str(pets['willie']['vaccinated']))
vaccinated: True

Dictionaries

Dictionaries in a dictionary

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

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

Or

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

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

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Dictionaries in a dictionary

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

Dictionaries

Creating dictionaries through a loop

We can create dictionaries using a loop:

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:

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 just got the vaccine.

How would you change that within the dictionary?

Dictionaries

Exercise 1 Solution

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

How would you change that within the dictionary?

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

Dictionaries

Exercise 2

How would you create a cumulative age given that the dogs are 1, 5 and 8 respectively?

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:

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

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 useful, but it can get unwieldy quickly.

Other data structures such as classes or databases could be useful to store information.

Sets

Introduction

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:

cities =  {'Madrid', 'Barcelona', 'Atlanta'}
cities
{'Atlanta', 'Barcelona', 'Madrid'}
cities = set(("Paris", "Lyon", "London", "Berlin"))
cities
{'Lyon', 'Paris', 'Berlin', 'London'}

Sets

Sets Example

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

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

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

or

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

Sets

Sets Example

Other examples of sets are:

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

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

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

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

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

Sets

Uses

Sets are particularly useful when we want to eliminate duplicates

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

Sets

Operations with Sets

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

Sets

Union

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:

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

Sets

Intersection

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:

set_intersection_operator = set_a & set_b
set_intersection_operator
{'cherry'}

Sets

Difference

The difference of two sets contains the elements that are in the first set but not in the second.

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
{'apple', 'banana'}
set_difference_operator = set_a - set_b
set_difference_operator
{'apple', 'banana'}

Sets

Symmetric Difference

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