Start learning free

LESSON 102 OF 344 · DICTIONARIES

Dictionary Length in Python: Counting Pairs with len()

Lesson Read the full explanation

In Python, you can get the number of key-value pairs in a dictionary using len():

scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
n = len(scores)
print(n)  # 3

len() works the same way on dictionaries as on lists and strings:

empty = {}
print(len(empty))  # 0

d = {"a": 1, "b": 2}
print(len(d))      # 2

Assignment
Follow the Coding Tutorial and get the number of entries in scores!


Hint
Use len(scores) and assign it to n.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · DICTIONARIES

    Dictionary Length in Python, explained

    Counting entries with len()

    The built-in len() function tells you how many key-value pairs a dictionary holds. Each pair counts once, no matter how large its value is:

    scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
    n = len(scores)
    print(n)  # 3
    

    This is the same len() you use on strings and lists. On a string it counts characters, on a list it counts items, and on a dictionary it counts pairs. You call it as a function, with the dictionary inside the parentheses, and not as a method like scores.len(), which does not exist.

    What gets counted

    The count is of keys, so it follows the rules for keys. An empty dictionary has length 0, and a value that is itself a collection still counts as one pair:

    empty = {}
    print(len(empty))  # 0
    
    d = {"a": 1, "b": 2}
    print(len(d))      # 2
    
    print(len({"a": [1, 2, 3, 4]}))  # 1
    

    The last line has a list of four numbers as the value, but there is only one key, so the length is 1.

    Length changes as the dictionary changes

    len() reports the size at the moment you call it. Adding a new key raises it, removing a key lowers it, and updating the value of an existing key leaves it unchanged:

    scores = {"Alice": 95, "Bob": 87}
    print(len(scores))      # 2
    
    scores["Alice"] = 99    # existing key, so the length stays the same
    print(len(scores))      # 2
    
    scores["Dan"] = 60      # new key
    print(len(scores))      # 3
    
    del scores["Bob"]       # remove a key
    print(len(scores))      # 2
    

    Duplicate keys never add to the count, because a key can exist only once. In the literal {"a": 1, "a": 2}, the second pair replaces the first, so len() returns 1.

    Looking up the length is fast: Python keeps the count and does not walk through the dictionary each time.

    Length across types

    Because len() is a general tool, the same call gives sensible answers for the types you have met so far, and each one counts its own kind of item:

    print(len("hello"))      # 5
    print(len([1, 2, 3]))    # 3
    print(len({"a": 1}))     # 1
    

    A dictionary has no gaps and no repeated keys, so its length is always exactly the number of keys you would get by looping over it.

    Common uses

    • Checking for emptiness. len(d) == 0 is true for an empty dictionary. A dictionary is also false in a condition when empty, so if not d: says the same thing.
    • Counting distinct items. If you record each item as a key while looping over a list, the final len() is the number of distinct items.
    • Averages. Dividing the sum of the values by len(scores) gives the mean score. For the three scores in this lesson, sum(scores.values()) / len(scores) is 84.66666666666667.

    Common mistakes

    • Expecting the sum of values. len({"a": 100}) is 1, not 100. It counts pairs, not what the values add up to.
    • Counting only the keys you meant. Keys differing by case, such as "Alice" and "alice", count as two entries.
    • Calling the wrong thing. len without parentheses is the function itself, not a number.
    • Using the length as an index. A dictionary has no positions, so scores[len(scores) - 1] does not mean "the last item". It looks for a key equal to that number and raises KeyError.

    The exercise, step by step

    The lesson starts with the scores dictionary of three students and asks for the number of entries.

    1. Call len. Pass scores in the parentheses. Python counts the pairs and gives back an integer.
    2. Store the result. Assign it to a new variable named n, below the dictionary.
    scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
    
    n = len(scores)
    

    The variable n is now the integer 3. It is a snapshot: if you add a pair to scores later, n still holds 3 until you call len(scores) again.

    Key takeaways

    • len(d) returns the number of key-value pairs in the dictionary.
    • An empty dictionary has length 0, and each key counts once whatever its value is.
    • Adding a new key increases the length; changing an existing key's value does not.
    • The result is a plain integer, not a live count, so call len() again after changes.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free