CS 100

Logo

Scientific Computing

Activity 22

Create a file called dictionary-practice.py and save in your cs100/ch4 folder.

  1. Write a function toPirate(str) and use a dictionary to solve problem 4.3 on pg 153 (end of chapter 4). Note: you may want to split a sentence into a list of words.

  2. Test your function with a few different inputs. For example:

    sentence = "hello there madam how are you"
    print( toPirate(sentence) ) # will print "avast there proud beauty how be you"
    

If you finish early

  1. Write a function combineDictionaries(d1, d2) that takes two dictionaries as parameters and returns a new dictionary that includes the items from both. Test your function with:
    nhl1 = {
        "Toronto": "Maple Leafs",
        "Montreal": "Canadiens",
        "Vancouver": "Canucks",
        "Boston": "Bruins",
        "Edmonton": "Oilers",
        "New York": "Rangers"
        }
       
    nhl2 = {
        "Detroit": "Red Wings",
        "Pittsburgh": "Penguins",
        "Philedlphia": "Flyers",
        "Calgary": "Flames",
        "Tampa Bay": "Lightning"
        }
    print( combineDictionaries(nhl1, nhl2) )
    
  2. Write a function swapKeyValues(myDictionary) that takes a dictionary as a parameter such that in the dictionary, the keys are names (as strings) and the values are phone numbers (also as strings). The function should return a new dictionary which swaps the key/value for each element. For example:
    people = { "Heather": "330-555-5555", "Bob": "206-111-2222", "Alice": "123-456-7890"}
    swapped = swapKeyValues(people)
    print(swapped) # {'330-555-5555': 'Heather', '206-111-2222': 'Bob', '123-456-7890': 'Alice'}
    

How to submit

Submit your working python file to Moodle.