Dictionaries

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? d = {"e": 9, "c": 3, "b": 2, "a": 5} print(len(d))

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Dictionaries explained

    A dictionary in Python stores pairs of keys and values. You look up a value by its key rather than by a position number, so a phone book is a natural dictionary: the name is the key and the number is the value. Keys must be unique and immutable, such as strings or numbers, while values can be of any type.

    Dictionaries are written in curly braces, with a colon between each key and its value, so the pair for apples might be written as "apple" followed by a colon and 3. Reading d[key] returns the value for that key, but it raises a KeyError if the key is missing. The get() method avoids this by returning a default value instead, as in d.get("kiwi", 0). Assigning d[key] = value adds the key if it is new and updates it if it already exists. del d[key] removes a pair. The keys(), values() and items() methods return views of the contents, and the in operator checks whether a key is present.

    Lookup by key is fast on average, which is why dictionaries are the usual way to count things or to store records with named fields. Since Python 3.7, a dictionary keeps its pairs in the order they were added.

    stock = {"apple": 3, "pear": 5}
    stock["apple"] = stock["apple"] - 1
    stock["plum"] = 2
    print(stock.get("kiwi", 0), len(stock))
    

    Worked example

    Trace the program above.

    1. The dictionary starts with apple at 3 and pear at 5.
    2. stock["apple"] - 1 is 3 - 1 = 2, so apple becomes 2.
    3. stock["plum"] = 2 adds a new key, so the dictionary now has three pairs.
    4. get("kiwi", 0) finds no kiwi key and returns the default 0.
    5. len(stock) is 3.

    The output is 0 3.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? d = {"a": 9, "d": 7, "e": 4, "c": 3} print(len(d))

    • Medium

      What does this Python code print? d = {"a": 7, "b": 8} d["a"] = 9 d["c"] = d["a"] + d["b"] print(d["c"])

    • Hard

      What does this Python code print? d = {"a": 5, "b": 3, "a": 8} print(len(d))