Dictionaries¶

🎨 {}¶

In [ ]:
meals = {
    'breakfast': 'oatmeal',
    'lunch': 'leftovers',
    'dinner': 'spaghetti'
}

NOTES

  • curly braces, colons, commas
  • key-value pairs
  • this is a dictionary or dict
In [ ]:
type(meals)
In [ ]:
meals
In [ ]:
meals['breakfast']

NOTES

  • What is this going to print?
  • square brackets for item lookup
  • you provide the key and you get the associated value back
In [ ]:
meals['lunch']
In [ ]:
meals['leftovers']

NOTES

  • You can only lookup by keys, not by values
  • When you try to lookup a key that is not in the dictionary, you get a KeyError
In [ ]:
for meal, offering in meals.items():
    print(f'For {meal} you get {offering}. 😋')
    
for meal in meals: # iterate over keys
    print(meal)
    
for dish in meals.values():  # iterate over values
    print(dish)

NOTES

  • meals.items() returns a sequence of key-value pairs, which we unpack into meal and offering
In [ ]:
list(meals.items())

🖌 in¶

In [ ]:
significance = {
    7: 'prime',
    2: 'even prime',
    3: 'prime',
    5: 'prime',
    9: 'even square',
    4: 'even square',
    1: 'multiplicative identity'
}

NOTES

  • we can use numbers as keys too, not just strings
In [ ]:
7 in significance
In [ ]:
8 in significance
In [ ]:
for number in range(10):
    if number in significance:
        print(f'{number} is {significance[number]}.')
    else:
        print(f"I don't know anything special about {number}.")

NOTES

  • We saw earlier that asking for a key-value that doesn't exist in a dictionary gives us a KeyError
  • Use key in dict syntax to check that the key is present
    • and if it isn't, do something else

🧑🏽‍🎨 The world needs more emojis¶

You are given a dictionary mapping words to emojis.

Replace all instances of a word with it's corresponding emoji. Ignore case.

So, given a dictionary

emojis = {'dog': '🐶', 'cat': '🐱', 'tree': '🌳', 'bird': '🐦'}

The phrase

My dog has fleas.

Becomes

My 🐶 has fleas.
In [ ]:
def add_emojis(text, emojis):
    """Replace words in `emojis` with their corresponding symbols."""
    words = text.split()
    new_words = []
    for word in words:
        if word.lower() in emojis:
            # replace
            new_words.append(emojis[word.lower()])
        else:
            # don't replace
            new_words.append(word)
        
    return ' '.join(new_words)
    
    
    
In [ ]:
def add_emojis(text, emojis):
    new_words = []
    for word in text.split():
        if word in emojis:
            word = emojis[word]
        new_words.append(word)
    return " ".join(new_words)
In [ ]:
emojis = {
    'dog': '🐶',   # This one will get overwritten
    'dog': '🐕',  
    'puppy': '🐶',
    'dogs': '🐶🐶',
    'cat': '🐱',
    'tree': '🌳',
    'bird': '🐦'
}
In [ ]:
add_emojis("The Dogs chased the cat which chased the bird that sat in the tree in my yard.", emojis)

🧑🏻‍🎨 Team Assignments¶

Community members want to register for the Rec Center sports teams.

You have a dictionary that maps age groups to team names.

Map a list of tuples containing a name and age to a list of tuples containing name and team.

To compute a participants age group, find the nearest multiple of 3 that is less than or equal to the participant age.

If the participant does not have an age-group assignment, they go in team "Adult League".

In [ ]:
age_groups = {
    0: 'Team Toddlers',
    3: 'Tiny Troupers',
    6: 'Starting Stars',
    9: 'Mighty Middles',
    12: 'Too Cool',
    15: 'Boundless'
}
participants = [
    ('Joe', 14),
    ('Jane', 6),
    ('Johnny', 4),
    ('Jennifer', 20),
    ('Jack', 16),
    ('Janice', 2)
]

def assign_teams(partipants, age_groups):
    """Return a list of (person, team) tuples"""
    teams = []
    for name, age in participants:
        # Find the age group (round down to nearest x3)
        age_group = (age // 3) * 3
        
        # Look up the team name
        if age_group in age_groups:
            your_team = age_groups[age_group]
        else:
            your_team = 'Adult League'
        teams.append((name, your_team))
    return teams
In [ ]:
def assign_teams(participants, age_groups):
    """Returns a list of tuples of name and team."""
    
    
    
    
    
    
In [ ]:
def assign_teams(participants, age_groups):
    result = []
    for name, age in participants:
        age_group = (age // 3) * 3
        group = age_groups.get(age_group, "Adult League")
        result.append((name, group))
    return result
In [ ]:
assign_teams(participants, age_groups)

👨🏾‍🎨 Cipher¶

Given a dictionary mapping letters to other letters (called a "codex"), encode a message.

The codex only contains lower-case letters, but you should encode upper-case letters also. Preserve casing.

In [ ]:
codex = {
 'a': 'd',
 'b': 'e',
 'c': 'z',
 'd': 'h',
 'e': 'g',
 'f': 's',
 'g': 'n',
 'h': 'r',
 'i': 'a',
 'j': 'b',
 'k': 'k',
 'l': 'j',
 'm': 'c',
 'n': 'u',
 'o': 'y',
 'p': 't',
 'q': 'q',
 'r': 'x',
 's': 'w',
 't': 'v',
 'u': 'p',
 'v': 'f',
 'w': 'i',
 'x': 'l',
 'y': 'm',
 'z': 'o'
}
In [ ]:
def encode(codex, message):
    """Return the encoded message using the codex to map letters."""
    encoded = ''
    
    for char in message:
        is_cap = char.isupper()
        
        if char.lower() in codex:
            char = codex[char.lower()]
        
        if is_cap:
            char = char.upper()
        
        encoded += char
        
    return encoded
        
    
    
    
    
    
    
    
    
In [ ]:
def encode(codex, message):
    result = ""
    for char in message:
        new_char = char
        if char.lower() in codex:
            new_char = codex[char.lower()]
        if char.isupper():
            new_char = new_char.upper()
        result += new_char
    return result
In [ ]:
encode(codex, 'I like fish.')

Key Ideas¶

  • dict {}
  • Iterating over the key-value pairs in a dictionary
  • key in dict
  • Lookup information using []