Skip to main content

Unit 5 · Gotta Catch 'Em All! · Lesson 42 of 57

Key to Success

The key to success

Lists are great when things are in order. But sometimes you want to look things up by name instead of by position.

Say we want to know everyone's role on the website. With a list, you'd have to remember that Amer is number 1. Gross.

Instead, Python has dictionaries:

roles = {
    "karl": "admin",
    "amer": "user",
    "zain": "admin",
    "alex": "banned",
}

A dictionary is made of key: value pairs, inside curly brackets {}.

Sound familiar? Remember Local Storage in Web Exploitation? Every row had a key (like user) and a value (like karl). Same idea! In fact, a lot of websites hand Local Storage data around in a format that looks almost exactly like a Python dictionary.

Looking things up

Put the key in square brackets, and you get its value back:

print(roles["zain"])
admin

Adding something new, or changing something, looks the same:

roles["rishabh"] = "user"   # new key, gets added
roles["alex"] = "user"      # existing key, gets changed (good behavior, I guess)

Careful!

Ask for a key that doesn't exist, and Python throws a KeyError:

print(roles["doug"])
KeyError: 'doug'

So check first! in asks whether a key is in the dictionary:

if "doug" in roles:
    print(roles["doug"])
else:
    print("Who's Doug?")

Looping through

Loop with .items() to get each key and value together:

for name, role in roles.items():
    print(f"{name} is a {role}")
karl is a admin
amer is a user
zain is a admin
alex is a banned

(The grammar's a bit rough, but you get the idea.)

Make a function called get_role that takes a username and returns their role from roles.

If the username isn't in roles, return "guest" instead of crashing.

get_role("karl")   # "admin"
get_role("doug")   # "guest"

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.