Computer Science 15-110, Fall 2010
Class Notes:  One-Dimensional Lists


  1. What is a dictionary?
  2. Quick Example
  3. How to...
    1.  Create a dictionary
      1.  Create an empty dictionary (with { })
      2. Create a dictionary from a list of tuples (with dict())
    2. Add a key/value
    3. Delete a key (with del, pop, and clear)
    4. Get a value from a key
    5. Get a value from a missing key
      1. Check if the key exists (with key in dict)
      2. Use dict.get(key) and dict.get(key, default)
    6. Modify a key/value
    7. Get all keys (with dict.keys())
  4. Usage
    1. Can use mixed types for keys and values
    2. Keys are case-sensitive
    3. Don't use a dictionary like a list
  5. Recommended Reading
  6. Examples Using Dictionaries
    1. Word Counts (from a list of words)
    2. Sparse Matrices
    3. Text Adventure
  7. Suggested Practice Problems

 Dictionaries
  1. What is a dictionary?
    1. It is a map from keys to values
    2. Adding, removing, getting, and setting are all fast (eg, much faster than using a sorted list of tuples)
    3.  Keys are a set:  they are unique and unsorted

  2. Quick Example

    # Quick Example using a dictionary
    says = { }             # creates an empty dictionary
    says["dog"] = "woof"
    says["cat"] = "meow"
    print says["dog"]      # woof
    print says["cat"]      # meow

    print ("cow" in says)  # False
    says["cow"] = "moo"
    print ("cow" in says)  # True
    print says["cow"]      # moo

    print says             # {'dog': 'woof', 'cow': 'moo', 'cat': 'meow'}

    says["dog"] = "bark"
    print says["dog"]      # bark
    print says             # {'dog': 'bark', 'cow': 'moo', 'cat': 'meow'}

  3. How to...

    1.  Create a dictionary

      # Create an empty dictionary (with {})
      d = { }  # or d = dict()
      print d

      # Create a dictionary from a list of tuples (with dict())
      d = dict([("dog", 10), ("ant", 0), ("cat", 3)])
      print d


    2. Add a key/value

      # Add a key/value
      d = { }
      d["dog"] = 5
      d["cat"] = 7
      print d


    3. Delete a key (with del, pop, and clear)

      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d              # {'ant': 0, 'dog': 10, 'cow': 7, 'cat': 3}

      # Delete a key with del dict[key]
      del d["dog"]
      print d              # {'ant': 0, 'cow': 7, 'cat': 3}

      # Delete a key with dict.pop(key)
      value = d.pop("cat")
      print value          # 3
      print d              # {'ant': 0, 'cow': 7}

      # Delete all keys with dict.clear()
      d.clear()
      print d              # { }


    4. Get a value from a key

      # Get a value from a key with dict[key]
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d["dog"]   # 10


    5. Get a value from a missing key

      Problem:

      # Try to get a value from a missing key with dict[key]
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d["pig"]  # KeyError: 'pig'  (key not in dictionary!)


      Solutions:

      # Detect a missing key with (key in dict):
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      if ("pig" in d):
          print d["pig"]
      else:
          print "pig is not in", d

      # Get a value from a missing key with dict.get(key)
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d.get("dog")  # 10
      print d.get("pig")  # None

      # Get a value from a missing key with dict.get(key, default)
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d.get("dog", 42)  # 10
      print d.get("pig", 42)  # 42


    6. Modify a key/value

      # Modify a key/value
      d = { }
      d["dog"] = 5
      d["cat"] = 7
      print d

      d["dog"] = 42
      print d

    7. Get all keys (with dict.keys())

      # Get all keys
      d = dict([("dog", 10), ("ant", 0), ("cat", 3), ("cow", 7)])
      print d.keys()         # ['ant', 'dog', 'cow', 'cat']
      print sorted(d.keys()) # ['ant', 'cat', 'cow', 'dog']

  4. Usage

    1. Can use mixed types for keys and values

      # Can use mixed types for keys and values
      d = { }
      d["ant"] = True
      d[False] = 42
      d[999] = "gnu"
      print d   # {'ant': True, False: 42, 999: 'gnu'}

    2. Keys are case-sensitive

      # Keys are case-sensitive
      d = { }
      d["ant"] = 3
      d["Ant"] = 4
      print d["ant"]  # 3
      print d["Ant"]  # 4
      d["cow"] = 32
      print d["COW"]  # crashes with KeyError, "COW" is not in the dictionary


    3. Don't use a dictionary like a list

      # Don't use a dictionary like a list
      # eg, the following code is discouraged:
      def exampleOfIncorrectUseOfDictAsList():
          d = { }
          n = 4
          print "Enter", n, "strings: "
          for i in range(n):
              value = raw_input("Enter string #" + str(i) + ": ")
              d[i] = value
          print "And here are the strings you entered:"
          for i in range(n):
              print i, d[i]

      exampleOfIncorrectUseOfDictAsList()


  5. Recommended Reading
    1. http://docs.python.org/library/stdtypes.html#typesmapping
    2. http://docs.python.org/tutorial/datastructures.html
    3. http://diveintopython.org/getting_to_know_python/dictionaries.html

  6. Examples Using Dictionaries
    1. Word Counts (from a list of words)  (wordCountsWithBug.py  and  wordCounts.py)
    2. Sparse Matrices  (sparseMatrices.py)
    3. Text Adventure  (textAdventure.py)

  7. Suggested Practice Problems
    1. More Sparse Matrix math (sparseMatrixAdd, sparseMatrixMultiply, sparseMatrixInverse, etc)
    2. contentsSortedByKey(dictionary):  Returns a list of the dictionary's key/value pairs (as tuples) with the keys in alphabetical order
    3. contentsSortedByValue(dictionary):  Returns a list of the dictionary's key/value pairs (as tuples) with the values in alphabetical order (this is a bit trickier)

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem