Concepts / Modifying and Deleting Dictionary Items

Modifying and Deleting Dictionary Items

Dictionaries are created empty using dict() or {} and store key-value pairs.

  • Programming
Interactive lab

Try it: Dictionary Operations

How a Python dict behaves under everyday operations: d[k] raises KeyError for a missing key while get() returns None or a default, in tests keys (not values), assignment adds a new key at the end but updates an existing key in place, del and pop remove pairs, and iteration, keys(), values() and items() follow insertion order — with keys() a live view and list(d.keys()) a frozen copy.

How it works

  1. A dict maps unique keys to values; the pairs are kept in the order the keys were first inserted (Python 3.7+).
  2. d[k] returns the value for k or raises KeyError: 'k'; d.get(k) returns None and d.get(k, default) the default instead.
  3. k in d tests the keys only; testing a value needs v in d.values(); len(d) counts pairs.
  4. d[k] = v adds a new pair at the end when k is new, and replaces the value in place (same position) when k already exists; update() does this for each pair.
  5. del d[k] and d.pop(k) remove a pair (KeyError if missing; pop returns the value, or the default if one is given).
  6. keys(), values() and items() are views of the current dict; list(d.keys()) copies the keys at that moment. Filtering builds a NEW dict of the pairs that pass a test.

Default run (3 steps): d = {'apple': 3, 'fig': 7, 'pear': 5} — 3 key-value pairs, kept in insertion order. Choose an operation. Example: d.get('kiwi', 0). … The key is missing, so get returns the default 0 instead of raising KeyError. d is not changed.

Simplified: String keys (short lowercase words) and small int values, at most 8 pairs. The lab models what the operations do, not how CPython stores the dict (see the hashing lab for that). Every operation's result, error text, printed output and view contents match CPython 3.12 on 150 random operation sequences.

Educational simulation

Loading the simulation…

From Empty to Populated

A dictionary begins as a container for key-value pairs. It can be created empty with dict() or with curly brackets, {}. Once the empty dictionary exists, square bracket assignment connects a key with a value. The dictionary then contains the pair that was assigned.

{}empty dictionary{'color': 'blue'}one key-value pairassign color
What changes in a dictionary before and after a value is assigned to a key?

Creating the Container

The two empty-dictionary forms are dict() and {}. They use different notation, but both create an empty dictionary. This gives you two equivalent starting points before any key-value pairs are added.

SyntaxStarting contentsPurpose
dict()No key-value pairsCreate an empty dictionary
{}No key-value pairsCreate an empty dictionary

Both supported forms create an empty dictionary.

After creation, square bracket assignment uses the form dictionary[key] = value. The key appears inside square brackets, and the value appears to the right of the assignment symbol. For example, starting with an empty dictionary named settings, the assignment settings['theme'] = 'dark' adds the key-value pair theme and dark.

Tracing Several Assignments

Worked example

Building a Small Dictionary

Start with an empty dictionary and add the pairs name and Mira, level and 3, and active and True.

  1. 1
    Start

    Use either dict() or {} to create the empty dictionary.

  2. 2
    First assignment

    Assign Mira to the key name. The dictionary now contains one key-value pair.

  3. 3
    Second assignment

    Assign 3 to the key level. A second key-value pair is added.

  4. 4
    Third assignment

    Assign True to the key active. A third key-value pair is added.

Result

The resulting dictionary is {'name': 'Mira', 'level': 3, 'active': True}.

The example shows the state changing one assignment at a time. Each square bracket expression identifies the key whose value is being assigned. The resulting dictionary contains the key-value pairs that were added.

Insertion Order and Display

In Python 3.7 and later, dictionaries preserve insertion order. This means that items appear in the sequence in which they were added. If name is added first, level second, and active third, the dictionary's items appear in that same sequence.

nameMiralevel3activeTrueadded nextadded next
In what order do key-value pairs appear after three assignments?

A dictionary's output format shows key-value pairs inside curly brackets. Pairs are separated by commas, and each key is connected to its value with a colon. Because this displayed format is also valid input syntax, the shown structure can be used to create a dictionary with multiple items at once.

Worked example

Reading Output as Input

Use the displayed dictionary {'city': 'Lima', 'visits': 2} as a model for creating a dictionary with two items at once.

  1. 1
    Identify the container

    The curly brackets show that the structure is a dictionary.

  2. 2
    Identify each pair

    city is connected to Lima, and visits is connected to 2.

  3. 3
    Preserve the written sequence

    The city pair appears first and the visits pair appears second.

Result

The same key-value structure serves as both dictionary output and valid input syntax.

Mistakes to Avoid

  • Common mistake

    Assuming dict() and {} create different kinds of empty containers.

    What it looks like
    Treating dict() as a non-dictionary because it uses parentheses.
    Why it fails

    The source material identifies both forms as ways to create an empty dictionary.

    Do this instead

    Recognize dict() and {} as two supported syntaxes for the same starting purpose.

  • Common mistake

    Leaving out the square brackets when assigning a key.

    What it looks like

    Writing dictionary = 'value' instead of dictionary[key] = value.

    Why it fails

    The documented assignment form places the key inside square brackets before the assignment symbol.

    Do this instead

    Use dictionary[key] = value when adding a key-value pair.

  • Common mistake

    Expecting dictionary items to appear in an arbitrary order.

    What it looks like

    Expecting the last-added item to appear first in Python 3.7 or later.

    Why it fails

    Python 3.7 and later preserve insertion order.

    Do this instead

    Track the order in which pairs were added.

  • Common mistake

    Treating displayed dictionary output as unrelated formatting.

    What it looks like

    Ignoring the braces, colons, and commas when using a displayed dictionary as a model.

    Why it fails

    The dictionary output format is also valid input syntax.

    Do this instead

    Read the displayed form as a key-value structure that can create a dictionary with multiple items.

  • Common mistake

    Guessing deletion syntax from this lesson.

    What it looks like

    Adding an unprovided deletion command to a solution.

    Why it fails

    The supplied source material explains creation, assignment, order, and output/input format, but does not state a deletion operation.

    Do this instead

    Use only deletion syntax provided by a separate, authoritative lesson.

EASY

A dictionary starts empty. Describe the state after adding the pair language and Python, followed by the pair version and 3.7. Which pair appears first, and which two syntaxes could have been used to create the empty dictionary?

Hints
  • Use square bracket assignment for each pair.
  • Use insertion order to determine which pair appears first.
  • The two empty-dictionary forms are dict() and {}.

Key Takeaways

  1. 1
    dict() and {} both create an empty dictionary.
  2. 2
    Square bracket assignment uses dictionary[key] = value to add a key-value pair.
  3. 3
    Python 3.7 and later preserve the order in which dictionary items are inserted.
  4. 4
    A dictionary's displayed key-value format is also valid syntax for creating a dictionary with multiple items.
  5. 5
    The supplied source material does not define deletion syntax, so deletion should be learned from a separate documented operation.

At a glance

  • Create an empty dictionary with dict() or {}.
  • Add key-value pairs through square bracket assignment.
  • Rely on insertion order in Python 3.7 and later when interpreting item order.
  • Recognize dictionary output as valid input syntax.
  • Do not assume deletion syntax that the source material has not specified.

More concepts starting with M