Defining Dictionaries (Key-Value Braces)

🏷️ Dictionaries / Creating and Accessing Dictionaries

🌱 Context Introduction

Dictionaries are one of Python's most powerful and flexible data structures. Unlike lists that use numeric indexes, dictionaries store data in key-value pairs — think of it like a real-world dictionary where you look up a word (the key) to find its definition (the value). For engineers working with configuration data, API responses, or system mappings, dictionaries provide an intuitive way to organize and access information.


⚙️ What is a Dictionary?

A dictionary is defined using curly braces {} with each item consisting of a key followed by a colon : and then its value. Multiple items are separated by commas.

Key characteristics: - Keys must be unique — no duplicate keys allowed - Keys are immutable — typically strings, numbers, or tuples - Values can be any data type — strings, numbers, lists, even other dictionaries - Dictionaries are unordered (in Python 3.6 and earlier) but maintain insertion order in Python 3.7+


🛠️ Basic Dictionary Syntax

A simple dictionary looks like this:

Example: A server configuration dictionary - Key: "hostname"Value: "web-server-01" - Key: "ip_address"Value: "192.168.1.100" - Key: "os"Value: "Ubuntu 22.04" - Key: "cpu_cores"Value: 4 - Key: "is_active"Value: True

The dictionary would be written as: server_config = {"hostname": "web-server-01", "ip_address": "192.168.1.100", "os": "Ubuntu 22.04", "cpu_cores": 4, "is_active": True}


📊 Key-Value Pair Breakdown

Component Description Example
Key The identifier used to look up data "hostname", "ip_address"
Colon Separates the key from its value :
Value The data associated with the key "web-server-01", 4
Comma Separates each key-value pair ,
Curly Braces Encloses the entire dictionary { }

🕵️ Creating Empty Dictionaries

There are two ways to create an empty dictionary:

  • Method 1: Use empty curly braces: empty_dict = {}
  • Method 2: Use the built-in dict() function: empty_dict = dict()

Both produce the same result — a dictionary with no key-value pairs.


🧩 Dictionaries with Mixed Data Types

Dictionaries can hold values of different types within the same structure:

Example: A service monitoring dictionary - "service_name""nginx" (string) - "port"80 (integer) - "is_running"True (boolean) - "dependencies"["database", "redis"] (list) - "config"{"worker_processes": 4, "max_connections": 1024} (nested dictionary)

Written as: service_info = {"service_name": "nginx", "port": 80, "is_running": True, "dependencies": ["database", "redis"], "config": {"worker_processes": 4, "max_connections": 1024}}


🔑 Important Rules for Dictionary Keys

  • Strings as keys: Most common and readable — {"env": "production"}
  • Numbers as keys: Valid but less common — {1: "one", 2: "two"}
  • Tuples as keys: Allowed if they contain only immutable elements — {("us-east", "web"): "server-01"}
  • Lists as keys:Not allowed — lists are mutable and will cause a TypeError
  • Dictionaries as keys:Not allowed — dictionaries are also mutable

🎯 Common Use Cases for Engineers

Use Case Example Dictionary
Server inventory {"server_id": "SVR-001", "location": "us-east-1", "status": "running"}
API response {"status_code": 200, "message": "success", "data": {"user": "admin"}}
Configuration settings {"log_level": "INFO", "max_retries": 3, "timeout": 30}
Environment variables {"DB_HOST": "localhost", "DB_PORT": 5432, "DB_NAME": "app_db"}

💡 Quick Tips for Beginners

  • Always use meaningful key names that describe the data they hold
  • Keep keys consistent — use either all lowercase or follow a naming convention
  • Remember that dictionaries are mutable — you can change values after creation
  • Use the len() function to count key-value pairs: len(server_config) returns 5
  • To check if a key exists, use the in operator: "hostname" in server_config returns True

✅ Summary

  • Dictionaries use {key: value, key: value} syntax
  • Keys are unique and immutable; values can be any data type
  • Dictionaries are ideal for structured data and lookup operations
  • Use curly braces {} to define them, with colons separating keys from values
  • Empty dictionaries can be created with {} or dict()

Dictionaries are your go-to tool whenever you need to map one piece of information to another — a fundamental skill for any engineer working with data in Python.


A dictionary is a collection of key-value pairs enclosed in curly braces {} that lets engineers store and retrieve data using meaningful labels instead of numeric indexes.


🟢 Example 1: Creating an empty dictionary

This example shows how to create a dictionary with no items.

empty_dict = {}

📤 Output: {}


🟢 Example 2: Dictionary with one key-value pair

This example shows a dictionary storing a single piece of data using a key and its value.

server = {"name": "web-server-01"}

📤 Output: {'name': 'web-server-01'}


🟢 Example 3: Dictionary with multiple key-value pairs

This example shows a dictionary storing several related pieces of information about a server.

server = {
    "name": "web-server-01",
    "ip": "192.168.1.10",
    "status": "active"
}

📤 Output: {'name': 'web-server-01', 'ip': '192.168.1.10', 'status': 'active'}


🟢 Example 4: Dictionary with mixed data types

This example shows that dictionary values can be different types — strings, integers, booleans, and lists.

config = {
    "hostname": "db-primary",
    "port": 5432,
    "ssl_enabled": True,
    "allowed_ips": ["10.0.0.1", "10.0.0.2"]
}

📤 Output: {'hostname': 'db-primary', 'port': 5432, 'ssl_enabled': True, 'allowed_ips': ['10.0.0.1', '10.0.0.2']}


🟢 Example 5: Dictionary using variables as values

This example shows how engineers can use variables to build a dictionary dynamically.

server_name = "api-gateway"
server_port = 8080
server_region = "us-east-1"

server_info = {
    "name": server_name,
    "port": server_port,
    "region": server_region
}

📤 Output: {'name': 'api-gateway', 'port': 8080, 'region': 'us-east-1'}


📊 Comparison: Dictionary vs List

Feature Dictionary List
Structure Key-value pairs Ordered items
Access method By key (e.g., dict["name"]) By index (e.g., list[0])
Curly braces {} Yes No
Square brackets [] No Yes
Best for Labeled data Sequential data

🌱 Context Introduction

Dictionaries are one of Python's most powerful and flexible data structures. Unlike lists that use numeric indexes, dictionaries store data in key-value pairs — think of it like a real-world dictionary where you look up a word (the key) to find its definition (the value). For engineers working with configuration data, API responses, or system mappings, dictionaries provide an intuitive way to organize and access information.


⚙️ What is a Dictionary?

A dictionary is defined using curly braces {} with each item consisting of a key followed by a colon : and then its value. Multiple items are separated by commas.

Key characteristics: - Keys must be unique — no duplicate keys allowed - Keys are immutable — typically strings, numbers, or tuples - Values can be any data type — strings, numbers, lists, even other dictionaries - Dictionaries are unordered (in Python 3.6 and earlier) but maintain insertion order in Python 3.7+


🛠️ Basic Dictionary Syntax

A simple dictionary looks like this:

Example: A server configuration dictionary - Key: "hostname"Value: "web-server-01" - Key: "ip_address"Value: "192.168.1.100" - Key: "os"Value: "Ubuntu 22.04" - Key: "cpu_cores"Value: 4 - Key: "is_active"Value: True

The dictionary would be written as: server_config = {"hostname": "web-server-01", "ip_address": "192.168.1.100", "os": "Ubuntu 22.04", "cpu_cores": 4, "is_active": True}


📊 Key-Value Pair Breakdown

Component Description Example
Key The identifier used to look up data "hostname", "ip_address"
Colon Separates the key from its value :
Value The data associated with the key "web-server-01", 4
Comma Separates each key-value pair ,
Curly Braces Encloses the entire dictionary { }

🕵️ Creating Empty Dictionaries

There are two ways to create an empty dictionary:

  • Method 1: Use empty curly braces: empty_dict = {}
  • Method 2: Use the built-in dict() function: empty_dict = dict()

Both produce the same result — a dictionary with no key-value pairs.


🧩 Dictionaries with Mixed Data Types

Dictionaries can hold values of different types within the same structure:

Example: A service monitoring dictionary - "service_name""nginx" (string) - "port"80 (integer) - "is_running"True (boolean) - "dependencies"["database", "redis"] (list) - "config"{"worker_processes": 4, "max_connections": 1024} (nested dictionary)

Written as: service_info = {"service_name": "nginx", "port": 80, "is_running": True, "dependencies": ["database", "redis"], "config": {"worker_processes": 4, "max_connections": 1024}}


🔑 Important Rules for Dictionary Keys

  • Strings as keys: Most common and readable — {"env": "production"}
  • Numbers as keys: Valid but less common — {1: "one", 2: "two"}
  • Tuples as keys: Allowed if they contain only immutable elements — {("us-east", "web"): "server-01"}
  • Lists as keys:Not allowed — lists are mutable and will cause a TypeError
  • Dictionaries as keys:Not allowed — dictionaries are also mutable

🎯 Common Use Cases for Engineers

Use Case Example Dictionary
Server inventory {"server_id": "SVR-001", "location": "us-east-1", "status": "running"}
API response {"status_code": 200, "message": "success", "data": {"user": "admin"}}
Configuration settings {"log_level": "INFO", "max_retries": 3, "timeout": 30}
Environment variables {"DB_HOST": "localhost", "DB_PORT": 5432, "DB_NAME": "app_db"}

💡 Quick Tips for Beginners

  • Always use meaningful key names that describe the data they hold
  • Keep keys consistent — use either all lowercase or follow a naming convention
  • Remember that dictionaries are mutable — you can change values after creation
  • Use the len() function to count key-value pairs: len(server_config) returns 5
  • To check if a key exists, use the in operator: "hostname" in server_config returns True

✅ Summary

  • Dictionaries use {key: value, key: value} syntax
  • Keys are unique and immutable; values can be any data type
  • Dictionaries are ideal for structured data and lookup operations
  • Use curly braces {} to define them, with colons separating keys from values
  • Empty dictionaries can be created with {} or dict()

Dictionaries are your go-to tool whenever you need to map one piece of information to another — a fundamental skill for any engineer working with data in Python.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

A dictionary is a collection of key-value pairs enclosed in curly braces {} that lets engineers store and retrieve data using meaningful labels instead of numeric indexes.


🟢 Example 1: Creating an empty dictionary

This example shows how to create a dictionary with no items.

empty_dict = {}

📤 Output: {}


🟢 Example 2: Dictionary with one key-value pair

This example shows a dictionary storing a single piece of data using a key and its value.

server = {"name": "web-server-01"}

📤 Output: {'name': 'web-server-01'}


🟢 Example 3: Dictionary with multiple key-value pairs

This example shows a dictionary storing several related pieces of information about a server.

server = {
    "name": "web-server-01",
    "ip": "192.168.1.10",
    "status": "active"
}

📤 Output: {'name': 'web-server-01', 'ip': '192.168.1.10', 'status': 'active'}


🟢 Example 4: Dictionary with mixed data types

This example shows that dictionary values can be different types — strings, integers, booleans, and lists.

config = {
    "hostname": "db-primary",
    "port": 5432,
    "ssl_enabled": True,
    "allowed_ips": ["10.0.0.1", "10.0.0.2"]
}

📤 Output: {'hostname': 'db-primary', 'port': 5432, 'ssl_enabled': True, 'allowed_ips': ['10.0.0.1', '10.0.0.2']}


🟢 Example 5: Dictionary using variables as values

This example shows how engineers can use variables to build a dictionary dynamically.

server_name = "api-gateway"
server_port = 8080
server_region = "us-east-1"

server_info = {
    "name": server_name,
    "port": server_port,
    "region": server_region
}

📤 Output: {'name': 'api-gateway', 'port': 8080, 'region': 'us-east-1'}


📊 Comparison: Dictionary vs List

Feature Dictionary List
Structure Key-value pairs Ordered items
Access method By key (e.g., dict["name"]) By index (e.g., list[0])
Curly braces {} Yes No
Square brackets [] No Yes
Best for Labeled data Sequential data