To Lecture Notes

IT 211 -- Feb 25, 2019

Review Exercises

  1. What is a dictionary.
    Ans: It is an aggregate datatype that stores key-value pairs. The key and value are separated with a colon ( : ), the key-value pairs are separated by commas ( , ). The entire dictionary are delimited with curley braces ( { } ). Dictionaries are mutable (changeable).
  2. Check the datatype of this dictionary object:
    d = {'name': 'Alice', 'gender': 'F', 'age': 11}
    Ans:
    print(type(d))
    # Output:
    <class 'dict'>
    
  3. Write a script that prints the gender of the person encoded in the dictionary d. Ans:
    print(d['gender'])
    
  4. Add the phone number 333/444-5555 to the dictionary d. Ans:
    d['phone_number'] = '333/444-5555'
    
  5. Write a statement to check if 'age' is included in the dictionary d. Ans:
    print('age' in d)
    print('ssn' in d)
    # Output:
    True
    False
    

Project 6

Some Examples

Review Questions

  1. Write a script that creates a dictionary from the data in this input file pet-info.txt.
    # Initialize dictionary:
    d = { }
    
    # Open input file
    fin = open("pet-info.txt", "r")
    
    # Throw away first line
    fin.readline( )
    
    # Process information from file
    line = fin.readline( )
    while line != "":
        fields = line.split(",")
        key = fields[0].strip( )
        value = fields[1].strip( )
        d[key] = value
        line.readline( )
        
    fin.close( )
    print(d)