Concepts / Dictionary Methods

Dictionary Methods

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…

A Dictionary Before It Has Data

A dictionary begins as a container for key-value pairs. You can create that container empty, then add pairs one at a time. Python provides two forms for creating an empty dictionary: dict() and {}.

python
Output
{}
{}
dict()empty dictionary{}no key-value pairs{}empty dictionarycreatescreates
How do dict() and {} produce the same empty dictionary despite using different syntax?

Adding the First Pair

Square bracket assignment adds a key-value pair to a dictionary. The general form is dictionary[key] = value. The expression inside the brackets identifies the key, and the expression after the equals sign supplies the associated value.

Code walkthrough
profile = {}
profile["name"] = "Mira"
profile["level"] = 3
print(profile)
  1. 1
    profile = {} creates an empty dictionary.
  2. 2
    profile["name"] = "Mira" adds the key name with the value Mira.
  3. 3
    profile["level"] = 3 adds the key level with the value 3.
  4. 4
    print(profile) displays both key-value pairs in their insertion order.
Output
{'name': 'Mira', 'level': 3}
{}empty dictionaryprofile["name"] ="Mira"add one pairname: Mirafirst pairprofile["level"] = 3add another pairname: Mira, level: 3two pairsassignproducesassignproduces
How does assigning dictionary[key] = value change the dictionary, and where does the new key-value pair go?

Reading the Dictionary State

A dictionary is organized as key-value pairs. In the displayed form, each key is followed by its associated value, and multiple pairs appear together inside curly brackets. This makes the displayed dictionary easy to read as a representation of the data that was entered.

dictionarycollection of pairsnamekeyMiravaluelevelkey3valuecontainsassociated withcontainsassociated with
What does each key contain, what value is associated with it, and how are multiple pairs organized inside a dictionary?
Worked example

Building a Dictionary Step by Step

Create a dictionary containing a color and a quantity by starting with an empty dictionary.

  1. 1
    Start empty

    Use {} to create a dictionary with no key-value pairs.

  2. 2
    Add the color

    Use inventory["color"] = "blue" to add the key color and its value blue.

  3. 3
    Add the quantity

    Use inventory["quantity"] = 4 to add the key quantity and its value 4.

  4. 4
    Inspect the result

    The dictionary display contains both pairs inside curly brackets.

Result

{'color': 'blue', 'quantity': 4}

Insertion Order in Python 3.7 and Later

In Python 3.7 and later, dictionaries preserve insertion order. That means dictionary items appear in the sequence in which you added them. If one pair is added first and another pair is added second, the displayed dictionary keeps that order.

python
Output
{'first': 'open', 'second': 'save', 'third': 'close'}
first: openadded firstsecond: saveadded secondthird: closeadded thirdthenthen
What order are key-value pairs stored and displayed in after they are added one by one?

From Input Syntax to Display

The format Python displays for a dictionary is also valid input syntax for creating a dictionary with multiple items at once. Curly brackets surround the pairs, and each pair is written in key-value form. This gives you two connected ways to understand dictionaries: the displayed form shows the structure, and the same structure can be entered as dictionary input.

Before
settings = {}
settings["mode"] = "quiet"
settings["retries"] = 2

The dictionary is built through separate square bracket assignments.

After
settings = {"mode": "quiet", "retries": 2}

The same key-value pairs are written together in dictionary format.

{"mode": "quiet","retries": 2}input form{"mode": "quiet","retries": 2}displayed formsame dictionary format
How does entering key-value pairs correspond to the dictionary representation Python displays?

Mistakes with Dictionary Construction

  • Common mistake

    Using parentheses as though they were the empty-dictionary syntax.

    What it looks like
    items = ()
    Why it fails

    The two empty-dictionary forms covered here are dict() and {}.

    Do this instead
    Use items = dict() or items = {}.
  • Common mistake

    Leaving out the square brackets when adding a pair.

    What it looks like
    profile = {}
    profile "name" = "Mira"
    Why it fails

    A dictionary key is specified inside square brackets in the assignment form.

    Do this instead
    Write profile["name"] = "Mira".
  • Common mistake

    Expecting dictionary pairs to appear in a different order from the order of insertion in Python 3.7 and later.

    What it looks like
    data["second"] = 2
    data["first"] = 1
    Why it fails

    Python 3.7 and later preserve insertion order, so second appears before first in the displayed sequence.

    Do this instead

    Read the displayed order as the order in which the pairs were added.

  • Common mistake

    Treating the displayed dictionary format as unrelated to input syntax.

    What it looks like
    data = {"first": 1, "second": 2}
    Why it fails

    The dictionary representation shown by Python is also valid input syntax for creating multiple pairs at once.

    Do this instead

    Use the displayed key-value structure as a model for writing a dictionary literal.

Practice the State Changes

EASY

Create an empty dictionary using curly brackets. Add the pair "language": "Python", then add the pair "version": 3.7. Write the dictionary you expect Python to display and preserve in order.

Hints
  • Begin with settings = {}.
  • Use square bracket assignment for each pair.
  • Place the pair added first before the pair added second in the displayed dictionary.

What do you think happens?

What will Python display after these assignments?

record = {}record["topic"] = "dictionaries"record["length"] = 1

  • {"topic": "dictionaries", "length": 1}

  • {"length": 1, "topic": "dictionaries"}

Reveal answer
Answer:

{"topic": "dictionaries", "length": 1}

In Python 3.7 and later, dictionary items appear in the sequence in which they were added. topic was added before length.

Dictionary Construction Checklist

  1. 1
    Create an empty dictionary with dict() or {}.
  2. 2
    Add a key-value pair with dictionary[key] = value.
  3. 3
    In Python 3.7 and later, dictionary items appear in insertion order.
  4. 4
    A dictionary's displayed key-value format is also valid input syntax for creating multiple pairs at once.

Key Takeaways

  • dict() and {} both create empty dictionaries.
  • Square bracket assignment adds key-value pairs.
  • Python 3.7 and later preserve the order in which dictionary pairs are inserted.
  • The dictionary format Python displays can also be used as input syntax for multiple key-value pairs.

Related concepts

More concepts starting with D