Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
TypeError: invalid type for function invocation; cannot convert from MAP to FUNC (click for details)
Callstack:
    at (Template:Custom/Views/Header/LibreTexts_Holder), /content/body/pre, line 58, column 14
    at template()
    at (Template:Custom/Views/Header), /content/body/pre[2], line 2, column 9
    at (Bookshelves/Computer_Science/Programming_Languages/Python_Programming_(OpenStax)/10:_Dictionaries/10.03:_Dictionary_Operations), /content/body/div[3]/section[4]/div/div/div/iframe/@width
Engineering LibreTexts

10.3: Dictionary Operations

( \newcommand{\kernel}{\mathrm{null}\,}\)

Learning Objectives

By the end of this section you should be able to

  • Recognize that a dictionary object is mutable.
  • Evaluate dictionary items, keys, and values.
  • Demonstrate the ability to access, evaluate, and modify dictionary items.
  • Modify a dictionary by adding items.
  • Modify a dictionary by removing items.

Accessing dictionary items

In Python, values associated with keys in a dictionary can be accessed using the keys as indexes. Here are two ways to access dictionary items in Python:

  • Square bracket notation: Square brackets [] with the key inside access the value associated with that key. If the key is not found, an exception will be thrown.
  • get() method: The get() method is called with the key as an argument to access the value associated with that key. If the key is not found, the method returns None by default, or a default value specified as the second argument.

Ex: In the code below, a dictionary object my_dict is initialized with items {"apple": 2, "banana": 3, "orange": 4}. The square bracket notation and get() method are used to access values associated with the keys "banana" and "apple", respectively. When accessing the dictionary to obtain the key "pineapple", -1 is returned since the key does not exist in the dictionary.

    my_dict = {"apple": 2, "banana": 3, "orange": 4}
    print(my_dict["banana"]) # Prints: 3
    print(my_dict.get("apple")) # Prints: 2
    print(my_dict.get("pineapple", -1)) # Prints: -1
Checkpoint: Accessing dictionary items
Concepts in Practice: Dictionary items

Given the dictionary members = {"Jaya": "Student", "John": "TA", "Ksenia": "Staff"}, answer the following questions.

1.
What is the output of members["Jaya"]?
  1. 0
  • None
  • "Student"
  • 2.
    What is the output of members.get("jaya")?
    1. 0
    2. None
    3. "Student"
    3.
    What is the output of members.get("jaya", "does not exist")?
    1. "Student"
    2. "does not exist"
    3. None

    Obtaining dictionary keys and values

    Dictionary keys, values, and both keys and values can be obtained using keys(), values(), and items() function calls, respectively. The return type of keys(), values(), and items() are dict_keys, dict_values, and dict_items, which can be converted to a list object using the list constructor list().

    Example 10.1

    String template formatting for course enrollment requests

    A dictionary object with items {"a": 97, "b": 98, "c": 99} is created. Functions keys(), values(), and items() are called to obtain keys, values, and items in the dictionary, respectively. list() is also used to convert the output to a list object.

        dictionary_object = {"a": 97, "b": 98, "c": 99}
    
        print(dictionary_object.keys())
        print(list(dictionary_object.keys()))
        print(dictionary_object.values())
        print(dictionary_object.items())

    The above code's output is:

        dict_keys(["a", "b", "c"])
        ["a", "b", "c"]
        dict_values([97, 98, 99])
        dict_items([("a", 97), ("b", 98), ("c", 99)])
    Concepts in Practice: Dictionary keys and values

    Given the dictionary numbers = {"one": 1, "two": 2, "three": 3}, answer the following questions.

    4.
    What is the output type of numbers.keys()?
    1. dict_keys
  • dict_values
  • list
  • 5.
    What is the output of print(numbers.values())?
    1. [1, 2, 3]
    2. dict_keys([1, 2, 3])
    3. dict_values([1, 2, 3])
    6.
    What is the output of print(list(numbers.keys()))?
    1. ["three", "two", "one"]
    2. ["one", "two", "three"]
    3. dict_keys(["one", "two", "three"])

    Dictionary mutability

    In Python, a dictionary is a mutable data type, which means that a dictionary's content can be modified after creation. Dictionary items can be added, updated, or deleted from a dictionary after a dictionary object is created.

    To add an item to a dictionary, either the square bracket notation or update() function can be used.

    • Square bracket notation: When using square brackets to create a new key object and assign a value to the key, the new key-value pair will be added to the dictionary. my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict["pineapple"] = 1 print(my_dict) # Prints: {"apple": 2, "banana": 3, "orange": 4, "pineapple": 1}
    • update() method: the update() method can be called with additional key-value pairs to update the dictionary content. my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict.update({"pineapple": 1, "cherry": 0}) print(my_dict) # Prints: {"apple": 2, "banana": 3, "orange": 4, "pineapple": 1, "cherry": 0}

    To modify a dictionary item, the two approaches above can be used on an existing dictionary key along with the updated value. Ex:

    • Square bracket notation: my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict["apple"] = 1 print(my_dict) # Prints: {"apple": 1, "banana": 3, "orange": 4}
    • update() method: my_dict = {"apple": 2, "banana": 3, "orange": 4} my_dict.update({"apple": 1}) print(my_dict) # Prints: {"apple": 1, "banana": 3, "orange": 4}

    Items can be deleted from a dictionary using the del keyword or the pop() method.

    • del keyword: my_dict = {"apple": 2, "banana": 3, "orange": 4} del my_dict["orange"] print(my_dict) # Prints: {"apple": 2, "banana": 3}
    • pop() method: my_dict = {"apple": 2, "banana": 3, "orange": 4} deleted_value = my_dict.pop("banana") print(deleted_value) # Prints: 3 print(my_dict) # Output: {"apple": 2, "orange": 4}
    Checkpoint: Modifying dictionary items
    Concepts in Practice: Modifying a dictionary

    Given the dictionary food = {"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20"}, answer the following questions.

    7.
    Which option modifies the value for the key "Coconut soup" to "$11" while keeping other items the same?
    1. food = {""Coconut soup": "$15""}
  • food["Coconut soup"] = 11
  • food["Coconut soup"] = "$11"
  • 8.
    Which option removes the item "Butter Chicken": "$18" from the food dictionary?
    1. food.remove("Butter Chicken")
    2. del food["Butter Chicken"]
    3. del food.del("Butter Chicken")
    9.
    What is the content of the food dictionary after calling food.update({"Kabob": "$22", "Sushi": "$16"})?
    1. {"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$22", "Sushi": "$16"}
    2. {"Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20", "Sushi": "$16"}
    3. { "Sushi": "$16", "Coconut soup": "$15", "Butter Chicken": "$18", "Kabob": "$20"}
    Try It: Create a dictionary of cars step-by-step

    Follow the steps below to create a dictionary of cars and modify it step-by-step.

    1. Create an empty dictionary.
    2. Add a key-value pair of "Mustang": 10.
    3. Add another key-value pair of "Volt": 3.
    4. Print the dictionary.
    5. Modify the value associated with key "Mustang" to be equal to 2.
    6. Delete key "Volt" and the associated value.
    7. Print the dictionary content.
        Prints {"Mustang": 2}
    Try It: The number of unique characters

    Given a string value, calculate and print the number of unique characters using a dictionary.

        Input:
        string_value = "This is a string"
        Prints 10

    This page titled 10.3: Dictionary Operations is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.

    Support Center

    How can we help?