the full guide

Tuples, sets and dictionaries

The other three collections, and how to choose the right one.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

Which one do I use?

TypeLooks likeCan change?Duplicates?Use it for
list[1, 2, 3]YesAllowedAn ordered collection
tuple(1, 2, 3)NoAllowedFixed data, like a coordinate
set{1, 2, 3}YesRemovedUnique items
dict{"a": 1}YesKeys are uniqueLooking up by name

Tuples

tuples.py
point = (4, 7)
print(point[0])

x, y = point      # Unpacking
print(x, y)

try:
    point[0] = 9
except TypeError as error:
    print("Can't change a tuple:", error)

Output

4
4 7
Can't change a tuple: 'tuple' object does not support item assignment

Sets

sets.py
a = {1, 2, 3, 3, 3}
b = {3, 4}

print(len(a))           # Duplicates are gone
print(sorted(a | b))    # In either
print(sorted(a & b))    # In both
print(sorted(a - b))    # In a, not in b

Output

3
[1, 2, 3, 4]
[3]
[1, 2]

Dictionaries

dicts.py
student = {"name": "Riya", "age": 14, "marks": [78, 85]}

print(student["name"])
print(student.get("city", "Not given"))   # Safe if the key is missing

student["city"] = "Pune"                  # Add
student["age"] = 15                       # Change
del student["marks"]                      # Remove

for key, value in student.items():
    print(key, "->", value)

Output

Riya
Not given
name -> Riya
age -> 15
city -> Pune
word_count.py
# A classic: count words with a dictionary
text = "free money free prize free"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

Output

{'free': 3, 'money': 1, 'prize': 1}

Code challenge

Make a dictionary of 3 subjects and marks, then print the subject with the highest marks.

max(marks, key=marks.get) gives the key with the largest value.

Finished reading?