Start learning free

LESSON 100 OF 344 · DICTIONARIES

Accessing Dictionary Values in Python: [] and get()

Lesson Read the full explanation

Once you have a dictionary, you can access any value by its key using square bracket notation:

scores = {"Alice": 95, "Bob": 87, "Charlie": 72}

alice_score = scores["Alice"]  # 95
bob_score = scores["Bob"]      # 87

If the key does not exist, you get a KeyError. Use get() to avoid this:

score = scores.get("Diana", 0)  # returns 0 if "Diana" not found

You can also check if a key exists with in:

if "Alice" in scores:
    print(scores["Alice"])

Assignment
Follow the Coding Tutorial and access Alice's score from scores!


Hint
Use scores["Alice"] and assign it to alice_score.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · DICTIONARIES

    Accessing Dictionary Values in Python, explained

    Looking up a value by its key

    A dictionary maps keys to values, and the main reason to build one is to look values up again. You do that by writing the key in square brackets after the dictionary's name:

    scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
    
    alice_score = scores["Alice"]
    bob_score = scores["Bob"]
    print(alice_score, bob_score)  # 95 87
    

    The lookup does not remove anything: scores still holds all three pairs afterwards. The result is an ordinary value, and you can store it in a variable, print it or use it in a calculation. Lookups are fast, because Python finds the key directly instead of scanning the dictionary from the start.

    The key you write must match exactly. Keys are case sensitive, so scores["alice"] is not scores["Alice"], and a number key is not the same as a text key that looks like it.

    Using looked-up values

    A looked-up value behaves like any other value of its type, so you can compare it, add it to another one or print it. Looking up a key is also the usual way to read every entry: loop over the keys and look each one up.

    print(scores["Alice"] + scores["Bob"])    # 182
    print(scores["Alice"] > scores["Bob"])    # True
    
    for name in scores:
        print(name, scores[name])
    
    182
    True
    Alice 95
    Bob 87
    Charlie 72
    

    Looping over a dictionary gives its keys, in the order they were added. Inside the loop, scores[name] is safe because every key comes from the dictionary itself. The loop for name, score in scores.items(): gives you both at once and avoids the second lookup.

    When the key is missing

    If the key does not exist, square brackets raise a KeyError and the program stops:

    try:
        scores["Diana"]
    except KeyError as error:
        print("KeyError:", error)
    
    KeyError: 'Diana'
    

    Often a missing key is not a bug, and you want to carry on. Python gives you two ways to handle it.

    The get() method

    get() takes the key and, as an optional second argument, a default to use when the key is missing. It never raises an error:

    print(scores.get("Alice", 0))  # 95
    print(scores.get("Diana", 0))  # 0
    print(scores.get("Diana"))     # None
    

    Without the second argument, a missing key gives None, Python's value for "nothing here". Notice that get() does not add the missing key to the dictionary. It only reads.

    Checking with in

    The in operator tells you whether a key exists, so you can decide what to do before looking it up:

    if "Alice" in scores:
        print(scores["Alice"])  # 95
    
    print("Diana" in scores)    # False
    

    The operator checks the keys, not the values. 95 in scores is False, even though 95 is one of the values. To look among values, use 95 in scores.values(), which is True.

    Which one to use

    • Use d[key] when the key must be there. A KeyError then points straight at the bug, instead of letting a wrong value slip through.
    • Use d.get(key, default) when a missing key is normal and a fallback value makes sense, for example counting with counts.get(word, 0) + 1.
    • Use key in d when the program should take a different path depending on whether the key exists.

    Common mistakes

    • Using parentheses. A dictionary is not called. scores("Alice") raises a TypeError; lookups use square brackets.
    • Forgetting the quotes. scores[Alice] looks for a variable named Alice. The key is the string "Alice".
    • Treating a number key as text. If the keys are integers, write d[1], not d["1"].
    • Using a default of the wrong kind. A fallback of 0 makes sense for scores, but later code that expects text could break if it receives None.

    The exercise, step by step

    The lesson starts with the scores dictionary already written and asks for Alice's score.

    1. Write the lookup. Put "Alice" in square brackets after scores. The key exists, so the lookup is safe and get() is not needed.
    2. Store it. Assign the value to a new variable named alice_score, below the dictionary.
    scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
    
    alice_score = scores["Alice"]
    

    Now alice_score is the number 95. The dictionary is unchanged, and you can look up the other students the same way.

    Key takeaways

    • d[key] returns the value for a key and raises KeyError if the key is missing.
    • d.get(key, default) returns the default instead, or None if you give none.
    • key in d checks keys, not values.
    • Keys must match exactly, including case.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free