Dictionaries

How to store student info?

A better and cleaner way: a dictionary

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)

More dictionary operations

grades = {'Agrim':'B', 'Gagan':'A-', 'Tanish':'A', 'Punj':'A'}  #'Agrim' is a key, 'B' is a value (element)

Dictionary keys and values

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

Example: Three functions to analyze song lyrics

  1. create a frequency dictionary mapping str:int
  2. find word that occurs the most and how many times

Creating 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)

Fibonacci Recursive Code

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))