Creating and Using Dictionaries in Python

Dictionaries are one of the most powerful and versatile data structures in Python. They allow you to store key-value pairs, making it easy to organize and retrieve data efficiently.

What is a Dictionary?

A dictionary in Python is an unordered collection of items. Each item consists of a key and its corresponding value. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any type.

Why Use Dictionaries?

Creating a Dictionary

To create a dictionary, use curly braces {} and specify key-value pairs separated by commas. Here's an example:

# Creating a dictionary
person = {
    'name': 'Alice',
    'age': 25,
    'is_student': True
}
print(person)

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

Accessing and Modifying Data

You can access values using their keys or modify them as follows:

# Accessing a value
print(person['name'])  # Output: Alice

# Modifying a value
person['age'] = 26
print(person['age'])  # Output: 26

# Adding a new key-value pair
person['city'] = 'New York'
print(person)

Common Dictionary Methods

Dictionaries come with several built-in methods that simplify common tasks:

  1. keys(): Returns all the keys in the dictionary.
    print(person.keys())
  2. values(): Returns all the values.
    print(person.values())
  3. items(): Returns key-value pairs as tuples.
    print(person.items())
  4. get(key, default): Retrieves the value for a given key, or returns a default if the key doesn't exist.
    print(person.get('height', 'Not specified'))

Real-World Applications

Dictionaries are widely used in various scenarios, such as:

With these foundational skills, you're now ready to leverage dictionaries effectively in your Python projects!