We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Introduction to Dictionaries in Python

Dictionaries are one of the most powerful and flexible data structures in Python. They allow you to store key-value pairs, making data more structured and accessible.


What is a Dictionary?

A dictionary is a collection of key-value pairs. Each key is unique and maps to a specific value.

Example:

person = {
    "name": "Amina",
    "age": 28,
    "is_student": False
}
  • "name" is a key and "Amina" is its value.
  • "age" is a key and 28 is its value.
  • "is_student" is a key and False is its value.

Syntax

  • Dictionaries are defined using curly braces {}.
  • Keys and values are separated by colons :.
  • Each key-value pair is separated by commas.
dictionary_name = {
    key1: value1,
    key2: value2
}

Types of Values

Values in a dictionary can be:

  • Strings
  • Numbers
  • Booleans
  • Lists
  • Other dictionaries
  • Even functions!

Why Use Dictionaries?

Dictionaries are perfect when:

  • You want to store related information (like a user profile).
  • You want to access data by names (like "email" or "username"), not just positions like in a list.

They are fast, efficient, and readable.

Think About It

Why might a dictionary be better than a list in some cases?

Because you can access data directly using names instead of numeric indexes. For example: person["name"] is more meaningful than person[0].

Quick Practice

Create your own dictionary with at least three key-value pairs:

book = {
    "title": "Python Basics",
    "author": "Lance",
    "pages": 200
}
print(book["title"])

Exercise: Try It Yourself!

Create a dictionary for a product in a store. It should have the keys: "name", "price", and "stock". Then print out the name and price.