Dictionaries in Python

Dictionaries in Python

What Are Dictionaries?

  • A dictionary is a powerful data structure for storing data in key-value pairs.
  • Versatile for associating specific values with unique identifiers (e.g., words with definitions).
  • Unordered and mutable, allowing for fast lookups, insertions, and deletions.

Importance in Data Management

  • Ideal for scenarios like user IDs with user data or other associations.
  • Enable efficient organization and retrieval of related data.
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
{'name': 'Alice', 'age': 30, 'city': 'New York'}

Creating a Dictionary

Basic Syntax

  • Use curly braces {} with key-value pairs separated by colons.
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

Explanation

  • Keys and values can be of any data type (strings, integers, other dictionaries).
  • Example dictionary person contains keys "name", "age", and "city".

Accessing Values in a Dictionary

Accessing Values

  • Use square brackets [] to retrieve values by their keys.
print(person["name"])  # Output: Alice
print(person["age"])   # Output: 30
Alice
30

KeyError Handling

  • Accessing a non-existent key raises a KeyError.

Modifying a Dictionary

Modifying Dictionary Contents

  • Dictionaries are mutable; you can add, modify, or remove key-value pairs.

Adding a Key-Value Pair:

person["occupation"] = "Engineer"
print(person)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
{'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}

Modifying Values

person["age"] = 31
print(person)  # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
{'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}

Dictionary Methods

Built-in Methods

  • Python dictionaries have various built-in methods for data manipulation.

get() Method

  • Returns the value for a specified key, returning None if the key doesn’t exist.
age = person.get("age", "Not Found")
print(age)  # Output: 31
31

Example with get()

location = person.get("city", "Not Found")
print(location)  # Output: Not Found
New York

Dictionary Keys, Values, and Items

Keys, Values, and Items Methods

  • Retrieve keys, values, or key-value pairs as needed.

keys() Method

keys = person.keys()
print(keys)  # Output: dict_keys(['name', 'age', 'occupation'])
dict_keys(['name', 'age', 'city', 'occupation'])

values() Method

values = person.values()
print(values)  # Output: dict_values(['Alice', 31, 'Engineer'])
dict_values(['Alice', 31, 'New York', 'Engineer'])

Looping Through a Dictionary

Looping Techniques

  • Loop through dictionaries using a for loop to access keys or both keys and values.

Looping Through Keys

for key in person:
    print(key)  # Output: name, age, occupation
name
age
city
occupation

Looping Through Keys and Values

for key, value in person.items():
    print(f"{key}: {value}")
# Output:
# name: Alice
# age: 31
# occupation: Engineer
name: Alice
age: 31
city: New York
occupation: Engineer

Nesting Dictionaries

What Are Nested Dictionaries?

  • Dictionaries can contain other dictionaries, enabling complex data structures.
people = {
    "Alice": {
        "age": 30,
        "city": "New York"
    },
    "Bob": {
        "age": 25,
        "city": "Los Angeles"
    }
}

Accessing Nested Values

print(people["Alice"]["city"])  # Output: New York
New York

Dictionary Comprehensions

What Are Dictionary Comprehensions?

  • A concise way to create dictionaries by transforming or filtering data.

Syntax

{key_expression: value_expression for item in iterable if condition}

Example of Dictionary Comprehension

squares = {x: x ** 2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}