Concepts / List and Dictionary Literals

List and Dictionary Literals

There are four built-in data structures in Python list, tuple, dictionary and set . We will see how to use each of them and how they make life easier for us.

  • Programming

Why Two Different Data Structures?

Imagine you need to store information about a person. You could write down their name, address, and phone number in a list: ["Alice", "123 Main St", "555-1234"]. But when you read this list later, do you remember which position holds the name? Which holds the address? Now imagine storing 100 people this way — you would need to remember the exact order for every single person. Python offers a better tool for this: a dictionary, where you label each piece of data with a key. Instead of guessing positions, you ask for the value by name: {"name": "Alice", "address": "123 Main St", "phone": "555-1234"}. Both are built-in data structures, but they solve different problems.

Understanding List Literals

A list literal is a sequence of values enclosed in square brackets, separated by commas. Each value occupies a position (called an index), starting from 0. Lists are ordered, meaning the sequence matters, and they are mutable, meaning you can change, add, or remove elements after creation.

When you write a list literal, you are directly creating a list object in Python's memory. The syntax is straightforward: open bracket, values separated by commas, close bracket. The position of each value is its index. This index-based organization is what makes lists ideal for ordered collections where you need to access elements by their position.

[opens the list"apple"index 0,separator"banana"index 1,separator42index 2]closes the list
What does each symbol represent in a list literal, and how are values organized by position?

In the example above, the list contains three values: the string "apple" at index 0, the string "banana" at index 1, and the integer 42 at index 2. Notice that a list can hold different types of values — strings, numbers, even other lists. The commas separate each value, and the square brackets tell Python this is a list.

Understanding Dictionary Literals

A dictionary literal is a collection of key-value pairs enclosed in curly braces, where each key is paired with its value using a colon. Keys must be unique and immutable (usually strings or numbers). Dictionaries are unordered (though in Python 3.7+, insertion order is preserved), and they are mutable, meaning you can change, add, or remove key-value pairs after creation.

When you write a dictionary literal, you are creating a mapping from keys to values. Instead of relying on position, you use meaningful labels (keys) to retrieve data. This is far more readable and flexible than remembering index positions. The syntax uses curly braces, colons to separate keys from values, and commas to separate pairs.

{opens the dictionary"name"key:key-value separator"Alice"value,pair separator"age"key:key-value separator30value}closes the dictionary
What does each symbol represent in a dictionary literal, and how are key-value pairs structured?

In the example above, the dictionary contains two key-value pairs. The key "name" maps to the value "Alice", and the key "age" maps to the value 30. When you need to retrieve Alice's age later, you do not count positions — you simply ask the dictionary for the value associated with the key "age".

Accessing Data: Index vs. Key

The fundamental difference between lists and dictionaries becomes clear when you access data. With a list, you use an integer index in square brackets to retrieve the value at that position. With a dictionary, you use a key (usually a string) in square brackets to retrieve the associated value. Both use the same bracket notation, but what goes inside the brackets tells Python whether to look up a position or a key.

fruits0"apple"1"banana"2"cherry"
How does an integer index map to the actual value stored in a list?
person"name""Alice""age"30"city""New York"
How does a key map to the actual value stored in a dictionary?

In the list diagram, you retrieve "banana" by asking for index 1. In the dictionary diagram, you retrieve "Alice" by asking for the key "name". The list requires you to know the position; the dictionary requires you to know the label. This is why dictionaries are so powerful for real-world data — you work with meaningful names rather than counting positions.

Worked Example: Building and Accessing a Dictionary

Creating and Retrieving Dictionary Data

You need to store information about a book: its title, author, and publication year. Create a dictionary literal and then retrieve each piece of information.

Write the dictionary literal: Start with an open curly brace. Add the first key-value pair: "title" as the key and "1984" as the value, separated by a colon. Add a comma, then the next pair: "author" and "George Orwell". Add another comma and pair: "year" and 1949. Close with a curly brace. The result is {"title": "1984", "author": "George Orwell", "year": 1949}.

Assign to a variable: Store this dictionary in a variable called book. Now you can refer to it by name: book = {"title": "1984", "author": "George Orwell", "year": 1949}.

Access the title: Use the key "title" in square brackets: book["title"]. Python looks up the key "title" in the dictionary and returns the associated value, which is "1984".

Access the author: Use the key "author" in square brackets: book["author"]. Python returns "George Orwell".

Access the year: Use the key "year" in square brackets: book["year"]. Python returns 1949.

You now have a dictionary that stores related information under meaningful keys. Retrieving any piece of data is as simple as asking for the key by name, without needing to remember positions.

Comparing Lists and Dictionaries

CharacteristicListDictionary
SyntaxSquare brackets: [value1, value2, value3]Curly braces with colons: {key1: value1, key2: value2}
Access methodInteger index (position): list[0]Key (usually string): dict["key"]
OrderOrdered; position mattersUnordered (insertion order preserved in Python 3.7+)
Use caseSequences of similar items; when order mattersRelated data with meaningful labels; when you need named access
MutabilityMutable; can change, add, or remove elementsMutable; can change, add, or remove key-value pairs
Duplicate valuesAllowed; same value can appear multiple timesKeys must be unique; values can repeat

The Four Built-In Data Structures

Python provides four built-in data structures, each with its own strengths. Lists and dictionaries are the most commonly used, but tuples and sets serve important roles. Understanding when to use each one is a key skill.

Built-In DataStructuresListOrdered, mutable, indexedTupleOrdered, immutable, indexedDictionaryUnordered, mutable,key-basedSetUnordered, mutable, noduplicates
What are the key differences between list, tuple, dictionary, and set, and when would you use each one?
  • List: Use when you have a sequence of items where order matters and you might need to change the collection. Example: a to-do list, a shopping list, or scores in a game.
  • Tuple: Use when you have a fixed sequence of items that should not change. Example: coordinates (x, y), or the return value of a function that returns multiple values. Tuples are immutable, making them safer for data that should not be modified.
  • Dictionary: Use when you have related pieces of data that you want to access by meaningful names rather than positions. Example: a person's profile (name, age, email), or a phone book (name to phone number).
  • Set: Use when you need a collection of unique items and do not care about order. Example: finding unique words in a document, or checking membership quickly.

How Dictionaries Connect to Function Arguments

Dictionaries are more powerful than they first appear. If you have used keyword arguments when calling functions, you have already worked with dictionary concepts. When you define a function with parameters and call it with keyword arguments, Python internally uses a dictionary-like structure called the symbol table to map parameter names to their values. This is why dictionary syntax feels natural in Python — it mirrors how the language itself manages named data.

When you write a function like def greet(name, age): and call it with greet(name="Alice", age=30), Python creates an internal mapping of parameter names to values. This is conceptually identical to a dictionary where "name" maps to "Alice" and "age" maps to 30. Inside the function, when you access the variable name, you are essentially performing a key lookup in that internal dictionary.

Common Mistakes with Literals

  • Forgetting commas between list elements

    Python interprets this as a syntax error. Commas are required to separate elements.

    Fix: Always separate list elements with commas: [1, 2, 3]

  • Using square brackets for dictionaries

    Square brackets create lists, not dictionaries. Dictionaries require curly braces.

    Fix: Use curly braces for dictionaries: {"name": "Alice"}

  • Forgetting the colon in dictionary key-value pairs

    The colon is required to separate keys from values. Without it, Python cannot parse the dictionary.

    Fix: Always use a colon between key and value: {"name": "Alice"}

  • Using a mutable object (like a list) as a dictionary key

    Dictionary keys must be immutable (hashable). Lists can change, so they cannot be keys.

    Fix: Use immutable types as keys: strings, numbers, or tuples. For example: {(1, 2): "value"}

  • Assuming dictionaries are ordered in older Python versions

    In Python 3.6 and earlier, dictionaries did not preserve insertion order. In Python 3.7+, they do.

    Fix: If you need guaranteed order, use Python 3.7 or later, or use an OrderedDict from the collections module

Choosing Between a List and a Dictionary

The choice between a list and a dictionary depends on how you will access your data. If you are storing a sequence of similar items and will access them by position (first item, second item, etc.), use a list. If you are storing related pieces of information and will access them by meaningful names (the person's name, the person's age), use a dictionary. A good rule of thumb: if you find yourself writing comments like "index 0 is the name, index 1 is the age," you should probably use a dictionary instead.

Practice: Creating and Accessing Literals

EASY

Create a list literal containing the names of three colors. Then create a dictionary literal with three key-value pairs representing a student's information (name, student ID, and grade). Finally, write out how you would access the second color in the list and the student's grade from the dictionary.

Hints
  • For the list, remember that indices start at 0, so the second element is at index 1.
  • For the dictionary, use meaningful keys like "name", "id", and "grade".
  • To access the second color, use list_name[1]. To access the grade, use dict_name["grade"].

Summary

List and dictionary literals are two of Python's most essential tools for organizing data. Lists use square brackets and integer indices, making them ideal for ordered sequences. Dictionaries use curly braces and keys, making them ideal for related data accessed by name. Understanding the difference between index-based and key-based access is fundamental to writing clear, maintainable Python code. When you need to store a sequence, choose a list. When you need to store related information with meaningful labels, choose a dictionary. Python also provides tuples (immutable sequences) and sets (unordered collections of unique items) for specialized use cases, but lists and dictionaries will handle the vast majority of your data storage needs.

Key Takeaways

  • List literals use square brackets and store values in order, accessed by integer index starting at 0.
  • Dictionary literals use curly braces and store key-value pairs, accessed by key rather than position.
  • Lists are ideal for sequences where order matters; dictionaries are ideal for related data accessed by meaningful names.
  • Both lists and dictionaries are mutable, but dictionaries require unique keys while lists allow duplicate values.
  • Python also provides tuples (immutable sequences) and sets (unordered unique collections) for specialized use cases.