Jed Rembold & Fred Agbo
April 3, 2024
Project #3 ImageShop is ongoing and due next week Monday 8th Apr at 10pm
I encourage you to always attend classes and section meetings
Python dictionaries use squiggly brackets
{}
to enclose their contents
Can create an empty dictionary by providing no key-value pairs:
empty_dict = {}
If creating a dictionary with key-value pairs
:
,
generic_dict = {'Bob': 21, 0: False, 13: 'Thirteen'}
A = {True: 'Seth', False: 'Jesse'}
B = {'Jill': 13, 'Jack': 12}
C = {(1,2): {'x': 1}}
#X = {{'x': 1, 'y': 2}: 'Shark'}
Y = {[1,3,5]: 'Odd'}
Z = {'A': 13, 'B': 24, 'A': 15}
The fundamental operation on dictionaries is selection, which is
still indicated with square brackets:
[]
Dictionaries though are unordered, so it is not
a numeric index that goes inside the
[ ]
You instead use the key directly to select corresponding values:
>>> A = {'Jack': 12, 'Jill': 13}['Jack']
>>> print(A)
13
>>> B = {True: 13, 0: 'Why?'}[0]
>>> print(B)
Why?
If you attempt to index out a key that doesn’t exist:
A = {'Jack': 12, 'Jill': 13}
print(A['Jil'])
you will get an error!
If in doubt, check for the presence of a key with the
in
operator:
if 'Jil' in A:
print(A['Jil'])
>>> d = {}
>>> d['A'] = 10
>>> d['B'] = 12
>>> print(d)
{'A':10, 'B':12}
>>> d['A'] = d['B']
>>> print(d)
{'A':12, 'B':12}
Suppose we had a file of student ids and accompanying scores that we wanted to read into a dictionary and then access.
def read_to_dict(filename):
dictionary = {}
with open(filename) as f:
for line in f:
ID, score = line.strip().split(',')
dictionary[ID] = score
return dictionary
def get_student_score():
scores = read_to_dict('SampleGrades.txt')
done = False
while not done:
student_id = input('Enter a student id number: ')
if student_id == "":
done = True
else:
if student_id in scores:
print(f"Student got a {scores[student_id]}.")
else:
print(f"Student id {student_id} was not found in classlist")
What is the printed value of the below code?
A = [
{'name': 'Jill', 'weight':125, 'height':62},
{'name': 'Sam', 'height':68},
{'name': 'Bobby', 'height':72},
]
A.append({'weight':204, 'height':70, 'name':'Jim'})
B= A[1]
B['weight'] = 167
print([d['weight'] for d in A if 'weight' in d])
[100,204]
[156,173,204]
[100,167,173,204]
[125,167,204]
Frequently we might want to iterate through a dictionary, checking either its values or its keys
Python supports iteration with the
for
statement, which has the form of:
for key in dictionary:
value = dictionary[key]
code to work with that key and value
You can also use the .items
method to
grab both key and values together:
for key, value in dictionary.items():
code to work with that key and value
def get_students_with_score():
scores = read_to_dict('SampleGrades.txt')
done = False
while not done:
des_grade = input('Enter a letter grade: ')
if des_grade == "":
done = True
else:
for st_id, grade in scores.items():
if grade == des_grade.strip().upper():
print(f"{st_id} got a {grade}")
Method call | Description |
---|---|
len(dict) |
Returns the number of key-value pairs in the dictionary |
dict.get(key, value) |
Returns the value associated with the
key in the dictionary. If the key is not
found, returns the specified value, which is
None by default |
dict.pop(key) |
Removes the key-value pair corresponding to
key and returns the associated value. Will
raise an error if the key is not found. |
dict.clear() |
Removes all key-value pairs from the dictionary, leaving it empty. |
dict.items() |
Returns an iterable object that cycles through the successive tuples consisting of a key-value pair. |
While most commonly used to indicate mappings, dictionaries have seen increased use of late as structures to store records
Looks surprisingly close to our original template of:
boss = {
'name': 'Scrooge',
'title': 'founder',
'salary': 1000
}
Allows easy access of attributes without worrying about ordering
print(boss['name'])