dictionary

Python Dictionaries

Python Dictionaries

Dictionaries are unordered collections of key-value pairs. They allow you to store data in pairs, with a unique key for each value.

Creating a Dictionary

A dictionary is created by enclosing key-value pairs in curly braces:

      
        person = {
            "name": "Alice",
            "age": 25,
            "city": "New York"
        }
        print(person)
      
    

This creates a dictionary called person with three key-value pairs.

Accessing Dictionary Elements

You can access a value by referencing its key:

      
        name = person["name"]
        print(name)
      
    

This will print the value associated with the key "name", which is "Alice".

Activity

Try It Yourself!

Create a dictionary to store your favorite book, movie, and song. Print each one by accessing the values using their keys.

Quick Quiz

Quick Quiz

  1. What is a dictionary in Python?
  2. How do you access the value of a key in a dictionary?

Answers: A dictionary is a collection of key-value pairs. You access a value by using its associated key, e.g., person["name"].