A data-structure is a way of arranging and organizing data in a computer program
Python has several useful data-structures built into the language
One is a list (already covered)
Another, dictionary
Many data structures allow data to be stored and retrieved using a concept called mapping
Mapping is the process of associating one value with another (a key with a value)
Lists map keys to values too!
Indices of the list are the keys
Elements in the list are the values
Keys (indices) are used to acess or modify the elements in the list
Like lists:
Unlike lists:
Example (mapping strings to integers)
singers = { "Taylor Swift": 1989,
"JVKE": 2001,
"Bruno Mars": 1983}
# Using the key "JVKE"
# to lookup the number 2001
singers["JVKE"]
# Modifying the value associated with "Bruno Mars"
singers["Bruno Mars"] = 1985
# add a new key and value pair
singers["Doja Cat"] = 1995
print(singers)
{'Taylor Swift': 1989, 'JVKE': 2001, 'Bruno Mars': 1985, 'Doja Cat': 1995}
Attendance Evaluate the expression on Gradescope.
.append(value)
.remove(value)
.pop(index)
Adds a new key/value pair:
Changes value associated with a key:
Retrieves a value:
Removes a key/value pair:
in
operatorWith strings:
With lists:
Check if an item is a dictionary key:
It returns a dictionary
with the count of every vowel in the string
.
Use for
loop.
def count_vowels(string):
counts = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
for i in range(len(string)):
char = string[i]
if char in counts:
counts[char] += 1
return counts
def main():
assert count_vowels("") == {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}
assert count_vowels("pineapple") == {"a": 1, "e": 2, "i": 1, "o": 0, "u": 0}
main()
It returns the dictionary
with the count of every characters in the string
.
def count_chars(string):
counts = {}
for i in range(len(string)):
char = string[i]
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
def main():
assert count_chars("") == {}
assert count_chars("banana") == {"b": 1, "a": 3, "n": 2}
print("pass all test cases")
main()
pass all test cases