Activity 22

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

  1. 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. Call your function to test it. 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'}
    
  2. Write a function prettyPrint(myDictionary) that will print out all (key, value) pairs of the dictionary, each on a new line, so that they are sorted alphabetically by key AND the values appear on the same spot in each column. Test your function by observing the below function call and output. (Hint: convert your keys to a list AND properly justify the string).
    unsorted = { "John": 5, "Alice": 3, "Xavier": 3, "Bob": 5, "Carl": 4 }
    prettyPrint(unsorted)
    

    The above would output the following:

    Alice   -  3
    Bob     -  5
    Carl    -  4
    John    -  5
    Xavier  -  3
    
  3. Write a function addValues(myDictionary) that takes a dictionary as a parameter such that in the dictionary, the keys are names (as strings) and the values are salaries (as integers). Call your function to test it. The function should return the sum of all salaries. For example:
    personnel = { "Bob": 900, "Alice": 1100, "Eve": 1300 }
    allSalaries = addValues(personnel)
    print(allSalaries) # 3300
    

If you finish early

  1. Write a function createDictionary(n) that takes a positive integer as a parameter and returns a dictionary such that in the dictionary, the keys are all integers 1-n (as strings), and the values are the number squared (as strings). Call your function to test it. For example:
    numbers = createDictionary(8)
    print(numbers) # {'1': '1', '2': '4', '3': '9', '4': '16', '5': '25', '6': '36', '7': '49', '8': '64'}
    
  2. Write a function combineDictionaries(d1, d2) that takes two dictionaries as parameters and returns a new dictionary that includes the items from both. Call your function to test it. For example:
    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) )
    

How to submit

Submit your working python file to Moodle.