TracksPractical Coding FoundationsWorking With DataWhat Is a Dictionary?(4 of 9)

What Is a Dictionary?

Lists are great when you have ordered items, but sometimes you need to look things up by name rather than position. That's where dictionaries come in — they store key-value pairs.

Creating Dictionaries

A dictionary uses curly braces and pairs keys with values using colons:

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

Each key (like "name") maps to a value (like "Alice"). You look up values using their keys, not their position.

Keys and Values

Think of a dictionary like a real dictionary: you look up a word (the key) to find its definition (the value).

product = {
    "id": 123,
    "name": "Widget",
    "price": 9.99,
    "in_stock": True
}

Keys are usually strings, though they can be numbers or other immutable types. Each key must be unique — you can't have two "name" keys in the same dictionary.

Values can be anything: strings, numbers, booleans, lists, even other dictionaries.

When to Use Dictionaries vs Lists

Use a list when:

  • Order matters
  • Items are similar (all usernames, all scores)
  • You'll access items by position or loop through all of them

Use a dictionary when:

  • You want to look up values by name
  • Each item has a label or identifier
  • You're representing an object with properties

A list of temperatures makes sense: [72, 75, 68, 71]. But a person's information makes more sense as a dictionary — you want to ask "what's their name?" not "what's at position 0?"

Empty Dictionaries

You can create an empty dictionary and add to it later:

user = {}
user["name"] = "Bob"
user["email"] = "bob@example.com"

This is common when building up data as your program runs.

Order in Dictionaries

In Python 3.7 and later, dictionaries remember the order you added items. Earlier versions didn't guarantee order. For most purposes, you shouldn't rely on order — if order matters, a list might be more appropriate.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion