1/58
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
dictionaries
built-in data structures used to store data in key-value pairs
each key maps to a value, and the values can be accessed and modified using the key
How do you create dictionaries?
by enclosing key-value pairs in curly braces or by using the built-in dict() constructor
creating dictionary using curly braces
user_profile = {
"username": "coder123",
"followers": 2500,
"is_active": True
}creating dictionary using dict()
car_info = dict(brand="Ford", model="Mustang", year=1964)using dictionary with user input
word = input("Please type an English word: ")
if word in translation-dict:
print("Translation: ", translation_dict[word])
else:
print("Word not found")using strings as keys and integers as values
scores = {}
scores["Alice"] = 85
scores["Bob"] = 92
scores["Charlie"] = 78using integers as keys and lists as values
collections = {}
collections[1] = ["apple", "banana"]
collections[2] = ["pear", "peach", "plum"]
collections[3] = ["grape", "orange"]True or false: a key can appear multiple times in a dictionary
false
What happens if a new entry uses an existing key?
the original value is replaced
What is the output for this code?
translation_dict["big"] = "grande"
translation_dict["big"] = "enorme"
print(translation_dict["big"])enorme
True or false: all keys in a dictionary must be immutable
true
What data type cannot be used in dictionaries?
lists
What is the output for this code?
translation_dict[[1,2,3]] = 5TypeError: unhashabletype: ‘list’
What is the output for this code?
translation_dict = {"cat": "gato", "dog": "perro", "bird": "pájaro}
for key in translation_dict:
print("key:", key)
print("value:", translation_dict[key])key: cat
value: gato
key: dog
value: perro
key: bird
value: pájaro
How can you remove key_value pairs?
using del
What is the output for this code?
staff = {"Alan": "lecturer", "Emily": "professor", "David": "lecturer"}
del staff["David"]
print(staff){‘Alan’: ‘lecturer’, ‘Emily’: ‘professor’}
checking if a key exists before deletion
if "Paul" in staff:
del staff["Paul"]
print("Deleted")
else:
print("This person is not a staff member")What is the output for this code?
staff = {"Alan": "lecturer", "Emily": "professor", "David": "lecturer"}
removed = staff.pop("David", None)
if removed is None:
print("This person is not a staff member")
else:
print(removed, "removed")lecturer removed
What is the output for this code?
person1 = {"name": "Alice Smith", "height": 165, "weight": 68, "age": 29}
person2 = {"name": "Bob Johnson", "height": 180, "weight": 85, "age": 34}
person3 = {"name": "Catherine Lee", "height": 158, "weight": 54, "age": 22}
people = [person1, person2, person3]
for person in people:
print(person["name"])
combined_height = 0
for person in people:
combined_height += person["height"]
print("The average height is", combined_height/len(people))
Alice Smith
Bob Johnson
Catherine Lee
The average height is 167.6666666666666
key() method
returns a view object of all keys
values() method
returns a view object of all key-value pairs
items() method
returns a view object of all key-value pairs
What is the output for this code?
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())dict_keys([‘name’, ‘age’, ‘city’])
dict_values([‘Alice’, 25, ‘New York’])
dict_items([(‘name’, ‘Alice’),(‘age’, 25), (‘city’, ‘New York’)])
How do you check if a key is in a dictionary?
use the in keyword
How do you check if a value is in a dictionary?
use the in keyword with the values() method
What is the output for this code?
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print("name" in my_dict)
print(25 in my_dictTrue
True
get() method
used to retrieve a value for a given key
syntax: dict.get(key, default_value)
What is the output for this code?
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict.get("name")
print(my_dict.get("country", "USA")Alice
USA
setdefault() method
retrieves a value for a given key, and if the key does not exist, inserts the key with a specified value
syntax: dict.setdefault(key, default_value)
What is the output for this code?
my_dict = {"name": "Alice", "age": 25}
print(my_dict.setdefault("city", "New York"))
print(my_dict)New York
{‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
nested dictionary
dictionary within another dictionary
What is the output for this code?
family = {
"child1": {"name": "Alice", "age": 5},
"child2": {"name": "Bob", "age": 8}
print(family["child1"]["child2']Alice
How can dictionaries be used?
to count occurrences of each item (use.get()) and to categorize items by their intial letter
sets
built-in data structures that store unordered collections of unique items
True or false: sets can have duplicate items
false
True or false: the elements contained in a set must be of an immutable test
true
How can a set be created?
either by using the built-in set function or by using curly braces {}
What is the output for this code?
x = set(('dog','cat','bird','dog'))
print(x){‘dog’, ‘cat’, ‘bird’}
Why must an empty set be defined using the set() function?
because Python interprets empty curly braces as an empty dictionary
True or false: lists and dictionaries can be elements of a set
false; set elements must be mutable
What does the len() function return for a set?
its number of elements
What is the output for this code?
x = {'apple', 'banana', 'cherry'}
print(len(x))3
What is the output for this code?
x = {'apple', 'banana', 'cherry'}
print('banana' in x)
print('orange' in x)True
False
a|b or a.union(b)
returns a new set containing all unique items from two or more sets
What is the output for this code?
a = {'red', 'blue', 'green'}
b = {'green', 'yellow', 'purple'}
print(a|b){‘red’, ‘green’, ‘purple’, ‘blue’, ‘yellow’}
a & b or a.intersection() method
returns a set that contains all elements common to both a and b
What is the output for this code?
a = {1,2,3,4}
b = {2,4,6,8}
print(a & b){2, 4}
a-b or a.difference(b)
returns a set that contains items that only exist a and not in b
What is the output for this code?
a = {1,2,3,4}
b = {2,4,6,8}
print(a-b){1,3}
a^b or .symmetric_difference() method
returns a set that contains all elements in either a or b, but not both
What is the output for this code?
a = {1,2,3,4}
b = {2,4,6,8}
print(a^b){1, 3, 6, 8}
.isdisjoint() method
returns true if sets a and b don’t have any elements in common and their intersection is an empty set
What is the output for this code?
a = {1,2,3,4}
b = {2,4,6,8}
c = {1,2,3}
d = {7,8,9}
print(c.isdisjoint(d))
print(a.isdisjoint(b))True
False
dictionary comprehension
concise, single-line syntax used to create new dictionaries from an iterable
syntax: {key: value for variable in iterable}
What is the output for this code?
squares = {x: x*x for x in range(6)}
print(squares){0:0, 1:1, 2:4, 3:9, 4:16, 5:25}
What is the output for this code?
values = ['apple', 'banana', 'cherry']
dictionary = {i: value for i, value in enumerate(values)}
print(dictionary){0: ‘apple’, 1:’banana’, 2:’cherry’}
set comprehension
concise, single-line syntax used to create a new set from an existing iterable
written like list comprehensions but with curly braces instead of parentheses
What is the output for this code?
set1 = set([1,2,3,4,5])
set2 = {item for item in set1}
print(set2){1,2,3,4,5}
What is the output for this code?
set1 = set([1,20,2,40,3,50])
set2 = {item for item in set1 if item < 10}
print(set2){1, 2, 3}