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}