Concepts / Working with Python Dictionaries and Lists

Working with Python Dictionaries and Lists

json.loads() returns native Python data structures (lists and dictionaries), not JSON text.

  • Programming
Interactive lab

Try it: Parsing JSON into Python

How json.loads() reads JSON text token by token and builds Python dicts, lists, strings, numbers, True/False and None, how an access path like data["users"][0]["name"] walks that structure, and what json.dumps() writes back.

How it works

  1. The scanner reads the next token: a brace or bracket, a string in double quotes, a number, true / false / null, or a ',' / ':' delimiter.
  2. '{' starts a Python dict and '[' a list; both are pushed on a parse stack until their closing '}' or ']'.
  3. Inside a dict every key must be a double-quoted string followed by ':' and a value; items are separated by ','.
  4. Anything else stops the parse with JSONDecodeError, reporting the message, line, column and character position.
  5. The access path is applied one subscript at a time: dicts take keys (KeyError if missing), lists take integer indexes (IndexError if out of range).
  6. json.dumps() turns the Python objects back into JSON text (True → true, None → null), optionally indented.

Default run (43 steps): json.loads() receives 105 characters of text. The scanner starts at char 0 and reads one token at a time. … json.dumps(data, indent=2) turns the Python objects back into JSON text (171 characters): True → true, None → null, and strings get double quotes.

Simplified: Written from scratch to match CPython 3.12's json module (messages and positions checked against it); input is limited to 400 characters and 24 nesting levels, and the access path accepts only ["key"] and [index] subscripts. Python 3.13 reports a trailing comma in an object with a different message.

Educational simulation

Loading the simulation…

From JSON Text to Python Data

When JSON is received as text, it is not yet a Python list or dictionary that you can navigate with brackets. The json.loads() function parses that text and returns native Python data structures. Once parsing is complete, you work with the result using ordinary Python indexing rather than JSON-specific extraction methods.

JSON textraw stringjson.loads()parsePython listcontains dictionariesinputreturns
What changes when json.loads() converts raw JSON text into Python data?

Reading the Parsed Shape

The first step in extracting data is to understand the structure returned by parsing. In the source example, the variable info is a list containing two elements. The first element, info[0], is a dictionary with the keys id, x, and name. This tells you which kind of operation to use at each level: use a numeric index for the list, then use a key for the dictionary.

StructureIdentifier usedSource expression
ListNumeric positioninfo[0]
DictionaryKeyitem['key']

Lists are navigated by position; dictionaries are navigated by key.

Listindex: 0First elementinfo[0]Dictionarykey: nameChuckinfo[0]['name']usesuses
How are dictionary keys different from list indexes when identifying and retrieving values?

Following Each Bracket

Worked example

Finding the First User's Name

Retrieve the name stored in the first dictionary inside the parsed variable info.

  1. 1
    Start with the list

    The variable info is a list. The expression info[0] selects its first element.

  2. 2
    Inspect the selected element

    The first element is a dictionary containing the keys id, x, and name.

  3. 3
    Select the dictionary value

    The expression info[0]['name'] uses the name key to retrieve the value associated with it.

Result

The expression info[0]['name'] retrieves 'Chuck'.

Code walkthrough
info[0]
info[0]['name']
  1. 1
    The first bracket operation moves from the top-level list to its first dictionary.
  2. 2
    The second bracket operation moves from that dictionary to the value stored under name.
  • Selects the first element of the list.
  • Selects the value associated with the name key in that dictionary.
infotop-level list0first elementdictionaryid, x, namenameChuck[0]selects['name']
How does Python move through each list index and dictionary key to reach the target value?

Native Python After Parsing

After json.loads() has returned the parsed value, extraction uses Python syntax. You do not need to call the JSON library again to retrieve a value. Standard Python indexing, loops, and methods can work with the returned native structures.

JSON arraystructured JSON valuePython listindex accessJSON objectkeyed JSON valuePython dictionarykey accessparses toparses to
Which native Python structure corresponds to each structured JSON form described in this lesson?
Best practice

Inspect the structure returned by parsing before writing a longer extraction expression. Knowing whether the outer value is a list or dictionary tells you whether the next operation should use a numeric position or a key.

Mistakes with Nested Access

  • Common mistake

    Treating the parsed result as if it were still raw JSON text.

    What it looks like

    Trying to use JSON-specific extraction methods after json.loads() has already returned the data.

    Why it fails

    The parsed result is a native Python structure, so its values should be retrieved with Python indexing.

    Do this instead

    Use expressions such as info[0] and info[0]['name'].

  • Common mistake

    Using a dictionary key where a list position is required.

    What it looks like

    Skipping the numeric list index when the target dictionary is inside info.

    Why it fails

    The first level is a list, and the list must be narrowed to one element before its dictionary keys can be used.

    Do this instead

    Use the two stages: first info[0], then the dictionary key.

  • Common mistake

    Using a list index where a dictionary key is required.

    What it looks like

    Trying to identify the name value with a numeric position instead of the name key.

    Why it fails

    The selected element is a dictionary whose values are identified by keys.

    Do this instead

    Use info[0]['name'] to retrieve the value under the name key.

Practice the Navigation

EASY

Suppose info is the parsed list described in this lesson. Write the Python expression that selects the first element, and then write the chained expression that retrieves the first element's name value.

Hints
  • The first list element uses index 0.
  • The dictionary value is selected with the name key.
  • The complete chained expression combines both bracket operations.

What do you think happens?

What value does info[0]['name'] retrieve in the source example?

  • The first user's name, Chuck

  • The whole list

  • The first dictionary's id key

Reveal answer
Answer:

The first user's name, Chuck

info[0] selects the first dictionary, and ['name'] selects the value associated with that dictionary key.

Key Takeaways

  1. 1
    json.loads() converts JSON text into native Python structures rather than leaving the result as JSON text.
  2. 2
    A list is navigated by numeric position, such as info[0].
  3. 3
    A dictionary is navigated by key, such as item['key'].
  4. 4
    Chained indexing moves through nested structures one level at a time.
  5. 5
    After parsing, ordinary Python indexing, loops, and methods are used for data extraction.

At a glance

  • json.loads() returns native Python lists and dictionaries from parsed JSON data.
  • Use numeric indexes to select list elements and keys to select dictionary values.
  • Read chained expressions from left to right, narrowing the structure at each bracket operation.
  • Once parsing is complete, extract values with standard Python syntax rather than JSON-specific methods.

Related concepts

More concepts starting with W