Dictionaries

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Dictionaries

  • Dictionaries are a non-sequential data structure that stores key-value associations
    • key - a piece of data that can be found in the dictionary easily
    • value - a piece of data that is associated with the key
    • Each pair it stores is identified by a key, and has a value
  • There is no inherent order, cannot be thought of as “ordered”

Dictionaries

players = {"Messi": 10, "Ronaldinho": 10,
           "Maradona": 10, "Romario": 11, 
           "Cristiano Ronaldo": 7, "Mbappé": 10}
  • key values can only be immutable types
  • “mixed type” keys are allowed
  • keys cannot be duplicated
  • values van be any type (and mixed-type)
  • any number of pairs can be stored
  • contents can change over time

Dictionaries

Common use cases: store associations

vikings = {8: "Kirk Cousins", 33: "Dalvin Cook", 19: "Adam Thielen"}

JSON api requests: https://api.weather.gov/gridpoints/MPX/109,72/forecast

Basic Dictionary syntax

  • number of entries: len(dict)
  • check if key can be found: key in dict
  • get a value (by key):
    • dict[key] – crash if not found
    • dict.get(key, default) – default if not found

Basic Dictionary syntax

  • assign a value to a key: dict[key] = value
    • if key is new, len(dict) will increase
    • if key is not new, old value is removed
  • remove a key: (return old value)
    • del dict[key] – crash if not found
    • dict.pop(key, default) – default if not found

Dictionaries and Loops

4 syntax, 3 options

for key in dict: # Loop over keys: 
  code using key here
  
for key in dict.keys(): # Loop over keys:
  code using key here
  
for value in dict.values(): # Loop over values
  code using value here
  
for key, value in dict.items(): # Loop over keys, value pairs
  code using (key, value) here

Exercise (by Mario)

Write a function count_coins(coins) that counts U.S. coins in a list and returns a dictionary mapping coin names to the number of times they appear in the list of integers representing coin values (in cents). If no coins is represented in the argument list, its count should be zero.

The dictionary should use coin names, not values:

  • 1 → pennies
  • 5 → nickels
  • 10 → dimes
  • 25 → quarters

Exercise (by Mario)

Submit your count_coins.py file to gradescope.

Test case:

coins = [1, 25, 1, 25, 1, 10, 5]  
counted_coins = count_coins(coins) 
assert counted_coins == {"pennies": 3,
                         "quarters": 2,
                         "dimes": 1,
                         "nickels": 1}

Ignore values that do not match coin names in U.S. English.

Solution 1

Start with a populated dictionary:

def count_coins(coins):
    counts = {"pennies": 0,
              "quarters": 0,
              "dimes": 0,
              "nickels": 0}
    
    for coin in coins:
        if coin == 1:
            counts["pennies"] += 1
        elif coin == 5:
            counts["nickels"] += 1
        elif coin == 10:
            counts["dimes"] += 1
        elif coin == 25:
            counts["quarters"] += 1

    return counts

Solution 2

Start with an empty dictionary (will not pass all autograder tests):

def count_coins(coins):
    counts = {}
    
    for coin in coins:
        if coin == 1:
            counts["pennies"] = counts.get("pennies", 0) + 1
        elif coin == 5:
            counts["nickels"] = counts.get("nickels", 0) + 1
        elif coin == 10:
            counts["dimes"] = counts.get("dimes", 0) + 1
        elif coin == 25:
            counts["quarters"] = counts.get("quarters", 0) + 1

    return counts

Solution 3

Start with an empty dictionary (will not pass all autograder tests):

def count_coins(coins):
    counts = {}
    
    for coin in coins:
        match coin:
          case 1:
              counts["pennies"] = counts.get("pennies", 0) + 1
          case 5:
              counts["nickels"] = counts.get("nickels", 0) + 1
          case 10:
              counts["dimes"] = counts.get("dimes", 0) + 1
          case 25:
              counts["quarters"] = counts.get("quarters", 0) + 1

    return counts
  
if __name__ == "__main__":
    coins = [1, 25, 1, 25, 1, 10, 5]  
    counted_coins = count_coins(coins) 
    assert counted_coins == {"pennies": 3,
                             "quarters": 2,
                             "dimes": 1,
                             "nickels": 1}
    print(counted_coins)
{'pennies': 3, 'quarters': 2, 'dimes': 1, 'nickels': 1}