Python Data Structures
Dictionary and Tuples
Dictionary
• A dictionary is a key-value data structure.
• Instead of multiple data structures housing related information, we can put it in one,
and use strings to index instead of integers.
p0 p1 p2
first_names = [“Ada”, “Bill”, “Charlie”]
grades = [ 98.0, 45.0 , 63.2 ] ← The Issue
• Using multiple lists has issues:
• Each list must be the same length
• Need to ensure each index, I, over all lists refers to the same person.
• Difficult to modify information, iterate through many lists, ensure that data is not
damaged.
Dictionary • Why use this?
A List A Dictionary • Typically stores varied
0 Element 1 Key 1 Element 1 heterogeneous data.
1 Element 2 Key 2 Element 2
• Hard to keep track of which
is which element.
2 Element 3
Element
Key 3 Element 3 • What if you added to it
... ... ... ...
• Nicer to have a descriptor
attached to the data value.
Index Custom Label Element
as Index
Dictionary Example
• A dict stores pairs of data, comprised of: a key, and a value
my_dict = {} #Empty dict, just like lists
# Indentation is not important here.
# improves human readability.
student_records = { key1 is “Ada”
”Ada”: 98.0, val1 is 98.0
”Bill”: 45.0,
key3 is “Charlie” ”Charlie”: 63.2 <string key>: <val>
val3 is 63.2 comma between key-pair entries
}
except the last line!
Dictionary Lookup Keys can be Integer,
• Dictionary Lookup uses key type instead of integers Float, String, Boolean
type
• Looks up the key:
• If key exists, returns the value associated with it.
• If key isn’t found, get an error!
student_records = {
”Ada”: 98.0,
”Bill”: 45.0,
”Charlie”: 63.2
}
student_records[“Ada”] → 98.0
student_records[“Ashley”] → Error: KeyError
Operators on Dicts
• Add entries to a dictionary
student_records[“Ashley”] = “101.0”
#Definitely not cheating.
• Check if a key exists within a dictionary. “Rob” != “rob”
“Rob” in student_records → False Upper-case and lower-case
“Ashley” in student_records → True
are not the same!
• Delete an entry
del( student_records[“Ashley”] )
#Cheater gets removed!
student_records = {
”Ada”: 98.0,
”Bill”: 45.0,
”Charlie”: 63.2
}
Operators on Dicts
• Obtain an iterable of all the keys in dict
student_records.keys()
→ returns [“Ada”, “Bill”, “Charlie”] ← Keys are unique
• Obtain an iterable of all the values in dict
student_records.values()
→ returns [98.0, 45.0, 63.2] ← Values don’t have to be unique
• As of Python 3.7+, dictionary iteration order is guaranteed to be the order of insertion.
• Previously, keys, and values could return any order
• E.g, [“Bill”, “Charlie”, “Ada”] or [“Ada”, “Charlie”, “Bill”]
Operators on Dicts
• What if I want to iterate over the keys & the items, at the same time?
• We can use the .items() method
student_records = {
”Ada”: 98.0,
”Bill”: 45.0,
”Charlie”: 63.2
}
any variable names you want.
for k, v in student_records.items(): ← returns the key and value, pair.
print(k, v)
→ ”Ada” 98.0
→ ”Bill” 45.0
→ ”Charlie” 63.2
Tuples
• A tuple is an immutable ordered sequence of elements
• Once created, it cannot be modified like Lists or Dicts.
• Is represented with parentheses
my_tuple = ()
some_things = (“Breakfast”, 3, [])
some_things[0] → “Breakfast”
len( some_things ) →3
some_things[1] = 4 → ERROR. Cannot modify.
some_things + (“taco”, “tuesday”)
→ (“Breakfast”, 3, [], “taco”, “tuesday”)
Tuples
• How is this useful?
• Prevents modification after creation, guarantees it won’t change.
• Can be used as a convenient way to swap variables.
a = b
b = a # Won’t work!
temp = a
a = b
b = temp
# This works…
(a,b) = (b,a)
# Swaps them without extra variables!