Dictionaries

Python FundamentalsData StructuresFree Lesson

Advertisement

Introduction

Dictionaries store data in key-value pairs. They provide fast lookup using keys.

Creating Dictionaries

# Basic dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# From keys
keys = ["a", "b", "c"]
dict.fromkeys(keys, 0)

# Dict comprehension
squares = {x: x**2 for x in range(5)}

Dictionary Operations

person = {"name": "John", "age": 30}

# Accessing
print(person["name"])           # John
print(person.get("country", "USA"))  # USA (default)

# Adding/updating
person["email"] = "john@email.com"
person.update({"country": "USA"})

# Removing
del person["age"]
email = person.pop("email")

# Methods
print(person.keys())
print(person.values())
print(person.items())

Practice Problems

  1. Count word frequency in text
  2. Merge two dictionaries
  3. Invert dictionary (swap keys and values)
  4. Group items by category
  5. Implement phonebook using dictionary

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement