names = ['Agrim', 'Gagan', 'Tanish', 'Punj'] grade = ['B', 'A-', 'A', 'A'] course = ['COL100','MTL100','PHL100', 'HUL100']For example, Gagan scored an A- in MTL100.
def get_grade(student, name_list, grade_list, course_list): i = name_list.index(student) grade = grade_list[i] course = course_list[i] return (course, grade)
A better and cleaner way: a dictionary
0 --> Elem1 1 --> Elem2 2 --> Elem3 3 --> Elem4 ...Index (int) maps to element.
Key1 --> Elem1 Key2 --> Elem2 Key3 --> Elem3 Key4 --> Elem4 ...Custom index (by label) maps to element.
A Python dictionary
my_dict = {} # empty dictionary
grades = {'Agrim':'B', 'Gagan':'A-', 'Tanish':'A', 'Punj':'A'} #'Agrim' is a key, 'B' is a value (element)
coursegrades = {'Agrim': {'COL100':'B', 'MTL100':'A'}, 'Gagan':{'MTL100':'A-'}, 'Tanish':{'PHL100':'A'}, 'Punj':{'HUL100':'A'}} #'Agrim' is a key, dictionary {'COL100':'B', 'MTL100':'A'} is a value (element)
Dictionary lookup
grades = {'Agrim':'B', 'Gagan':'A-', 'Tanish':'A', 'Punj':'A'} #'Agrim' is a key, 'B' is a value (element)
grades['Gagan'] # evaluates to 'A-'
grades['Ashish'] # gives a KeyError
Dictionary operations
grades = {'Agrim':'B', 'Gagan':'A-', 'Tanish':'A', 'Punj':'A'} #'Agrim' is a key, 'B' is a value (element)
grades['Asmit'] = 'A'
'Gagan' in grades # evaluates to true 'Lakshay' in grades # evaluates to false
del(grades['Tanish'])
More dictionary operations
grades = {'Agrim':'B', 'Gagan':'A-', 'Tanish':'A', 'Punj':'A'} #'Agrim' is a key, 'B' is a value (element)
grades.keys() # returns ['Gagan', 'Agrim', 'Tanish', 'Punj']
grades.values() # returns ['A-', 'B', 'A', 'A']
Dictionary keys and values
int, float, string, tuple, bool)
d = {4:{1:0}, (1,3):"twelve", 'const':[3.14,2.7,8.44]}
list vs. dict
list |
dict |
|---|---|
| ordered sequence of elements | matches keys to values |
| look up elements by an integer index | look up one item (value) by another item (key) |
| indices have an order | no order is guaranteed |
| index is an integer | key can be any immutable type |
str:int(list, int) for (words_list, highest_freq).(list, int) containing the list of words ordered by their frequencyCreating a dictionary
def lyrics_to_frequency(lyrics):
myDict = {}
for word in lyrics: #can iterate over list
if word in myDict: #check if word in dictionary
myDict[word] += 1 #update value associated with word
else:
myDict[word] = 1
return myDict
Using the dictionary
def most_common_words(freqs):
values = freqs.values()
best = max(values) # values is an iterable, so can apply built-in function max
words = []
for k in freqs: #can iterate over keys in dictionary
if freqs[k] == best:
words.append(k)
return (words, best)
Leveraging dictionary properties
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w]) #can directly mutate dictionary; makes it easier to iterate
else:
done = True
return result
beatles = "....."
print words_often(beatles, 5)
def fib(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return fib(n-1) + fib(n-2)
This recursive implementation is inefficient
Fibonacci with a dictionary
def fib_efficient(n, d):
if n in d:
return d[n]
else:
ans = fib_efficient(n-1, d) + fib_efficient(n-2, d) #method sometimes called "memoization"
d[n] = ans
return ans
d = {1:1, 2:2}
print(fib_efficient(6, d))
fib(34) results in 11,405,773 recursive calls to the procedurefib(34) results in 65 recursive calls to the procedure