logo
Python Data Structures - Interview Questions and Answers
What is a dictionary in Python? How is it different from a list?
What is a Dictionary in Python?

A dictionary in Python is an unordered, mutable, and key-value paired data structure. It allows you to store and retrieve values using unique keys.

Syntax:

my_dict = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
  • Keys (e.g., "name", "age", "city") must be unique and immutable (strings, numbers, or tuples).
  • Values (e.g., "Alice", 25, "New York") can be any data type.

How is a Dictionary Different from a List?
Feature Dictionary (dict) List (list)
Structure Key-value pairs Ordered collection of elements
Access Elements my_dict["name"] (via keys) my_list[0] (via index)
Mutability Mutable (can update values) Mutable (can add/remove elements)
Ordering Maintains order (since Python 3.7+) Ordered
Duplicates Keys must be unique Can have duplicate elements
Use Case When data is labeled (e.g., user info) When data is sequential (e.g., numbers, items in a queue)

Example: Dictionary vs. List
# List Example (Indexed Access)
my_list = ["Alice", 25, "New York"]
print(my_list[0])  # Output: Alice

# Dictionary Example (Key-Based Access)
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict["name"])  # Output: Alice

* Dictionaries are best for labeled data (e.g., a database record).
* Lists are best for ordered collections (e.g., a list of items in a shopping cart).