PYW.png 7a: Sets and dictionaries

Table of Contents

1. Some first feedback about the exam

  • Too much (in terms of time)
  • No perfect numbers?

2. Sets

Sets are like lists:

  • They can contain multiple values
  • You can use "in" to check if a specific value is contained in it
lst = [1,2,4,5]
print(2 in lst)
  • You can add and remove values: sets and lists are mutable data types.

Remember: strings are not mutable:

str = "hiiii"
str[2] = "a"
st = ["hi", "all"]
st[0] = "hiiiii"
print(st)
  • You can put them in a for loop to do something with all of its values.

Sets are different from lists:

  • Any value can be in a set at most once. It is either in there or it isn't.
lst = [1,1,2,1]
  • Sets do not remember the order of values it contains.

You make a set like a list, except use curly brackets instead of square brackets:

example_set1 = { "Rick", "Morty", "Omni-man", "Ren", "Stimpy", 0, False, 4.5}
example_set2 = { "Jim", "Morty", "Omni-man", "Ren", "Stimpy" }

# u | v   the set of all values that are in u, or in v, or both
# u & v   the set of all values that are in both u and v
# u - v   the set of all values that are in u, but not in v

print(example_set1 | example_set2)
print(example_set1 & example_set2)
print(example_set1 - example_set2)

Figure out!! Why can I not add 1 to a set? Answer: because Python treats True as 1 and False as 0, and a set only contains one of them (so False or 0, and True or 1).

3. Intro to Dictionaries

A dictionary is much like a set, except that all values are now called the "keys" of the dictionary. Also, all keys now have an associateed "value".

Usually a key is a String. Values can be of any Data Type (Integer, Boolean, String, List, Tuples, other Dictionaries, etc.)

dict1 = {"key_name": 4, "key2": True}

Like sequences (List, String, Tuples), Dictionaries are iterable, but, in contrast to sequences, dictionaries are not ordered.

Sequence: An ordered collection of values where each value is identified by an integer index. (Downey, p. 101).
test = "hi all"

print(test[4])

lst = ["this","is","a","list"]

print(lst[2])

That means that you cannot access an item of a dictionary with an integer. Instead, you access an item of a dictionary with the key.

dict1 = {"item_45": 4, "key2": True}
print(dict1["item_45"])

One reason why Dictionaries are a populare Datatype is because accessing items happens relatively fast (more later).

4. Accessing the value of a key

Items are not indexed. You access a value of an item using its key.

shopping_list = {"apples": 4, "oranges" : 7}

print(shopping_list["oranges"])

It is case-sensitive:

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

print(shopping_list["raspberry_pi"])

5. A dictionary is mutable

A dictionary is mutable!

lst = [1,2,4,5]
lst[2] = 100
print(lst)
shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

shopping_list["raspberry_pi"] = 100

print(shopping_list)

6. <len> and <in> for dictionaries

Using the len() function returns the number of pairs/items in a dictionary.

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

print(len(shopping_list))

The in operator checks whether a key exists in a dictionary.

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

set1 = {"apples",5, True, "hi all"}

print("apples" in shopping_list)
print("apples" in set1)

7. Faster algorithm

The in operator uses different algorithms to search for an element in a list and a dictionary.

  • For lists, it employs a basic search algorithm. The longer the list is, the more time it will take to search.
  • For dictionaries, it employs a so-called hashtable algorithm. This has as a property that it is time-independent on the number of items in the dictionary.

8. Adding and deleting items

A new element can be added to a dictionary simply by introducing a new key-value pair:

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

shopping_list["oranges"] = 6

print(shopping_list)

To remove an element use the del command:

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

del shopping_list["apples"]

print(shopping_list)

9. Methods for dictionaries

9.1. get

Returns the corresponding value of the <key> if it exists!

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

print(shopping_list.get("apples"))

9.2. keys

Returns all the keys of the dictionary as an iterator.

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list.keys():
    print(i)
print("---this is the same ---")
for i in shopping_list:
    print(i)

9.3. values

Returns all the values of the keys of the dictionary as an iterator.

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list.values():
    print(i)

9.4. items

Returns a series of tuples, each containing a key-value pair from the dictionary. The output is also an iterator.

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list.items():
    print(i)

Why this is useful is shown further down below.

10. Looping through dictionaries

Like with a sequence, you can use a for-loop to loop through (traverse) a dictionary:

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list:
    print(i)

By default you will loop through the keys.

If you want to loop through the values, you can use the method .values():

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list.values():
    print(i)

print("---")

# This is the same by the way:

for i in shopping_list:
    print(shopping_list[i])

If you want to loop through both, you can use the method .items():

shopping_list = {"apples": 4, "rice": "2kg", "raspberry_pi": 3.14}

for i in shopping_list.items():
    print(i[0])
    print(i[1])
    print("---")

11. Some testing during the class (not exam material)

Python treates False and 0 as the same thing. So when printing the contents of a set, it only prints whichever came first in the definition of the dictionary:

set1 = {7, "lalal", 0, False}
set2 = {7, "lalal", False, 0}
print(set1)
print(set2)

In an if-statement python treats an empty string also as False:

if "":
    print("yes")
else:
    print("no")

But in forming sets it does not (as in, if you print the set, it both shows False and the empty string):

set1 = {"this", "is", "a", "test", False, ""}

print(set1)

Created: 2025-03-25 di 10:18