Objectives

  • Describe what a dictionary is in Python
  • Create a dictionary
  • Add an element to a dictionary
  • Remove an element from a dictionary
  • Access dictionary documentation
  • Get a list of the keys in a dictionary
  • Get a list of the values in a dictionary
  • Use dictionary comprehensions

Dictionary overview

  • a dictionary is an instance of the dict class
  • to get dictionary documentation: help(dict)
  • a dictionary is a comma separated list of key:value pairs surrounded by { }
  • dictionary lists are unordered
  • each dictionary element is a a key:value pair
  • the key must be an immutable object
  • the value may be mutable

Dictionary examples

help(dict) # display dictionary documentation courses = { # create a dictionary "CIS 101":"Introduction to Computers", "CIS 105":"Introduction to Windows", "CIS 111":"Program Logic and Design", "CIS 115":"Internet Fundamentals", "CIS 118":"Foundations of Web Design", "CIS 119":"JavaScript" }; print(len(courses)) # 6 print(courses[2]) # KeyError print(courses["CIS 111"]) # Program Logic and Design print(courses) # displays dictionary courses.keys() # returns a list of keys courses.values() # returns a list of values courses.items() # returns a list of tuples representing the dictionary entries # display the key and the value of all dictionary elements for cnum, cname in courses.items(): print("{0} is {1}".format(cnum, cname)) # add a dictionary element courses['CIS 123'] = "Management Information Systems" if "CIS 160" in courses: print(courses["CIS 160"]) # nothing displays if "CIS 111" in courses: print(courses["CIS 111"]) # Program Logic and Design del courses["CIS 115"] # delete a dictionary entry # Dictionary comprehension examples list1 = [1, 5, 12, 6] { item:item**2 for item in list1 } # {1: 1, 5: 25, 12: 144, 6: 36} { item:item**2 for item in list1 if item % 2 != 0 } {1: 1, 5: 25}