Python Creating Dictionaries
Introduction
A dictionary is one of Python’s most powerful and commonly used data structures. Dictionaries store data in key-value pairs, allowing you to quickly retrieve, update, and manage information.
Unlike lists, tuples, and sets, dictionaries use keys instead of indexes to access values. Each key in a dictionary must be unique.
Dictionaries are widely used in:
Automation testing
API response handling
Database records
Configuration management
Data analysis
Web development
Machine learning applications
In this tutorial, you will learn how to create dictionaries in Python, different ways to create them, practical examples, real-world applications, common mistakes, and best practices.
What is a Dictionary?
A dictionary is an unordered collection of key-value pairs enclosed within curly braces {}.
Example
student = {
"name": "John",
"age": 21,
"course": "Python"
}
print(student)
Output
{'name': 'John', 'age': 21, 'course': 'Python'}
Each key is associated with a specific value.
Creating a Simple Dictionary
Syntax
dictionary_name = {
key1: value1,
key2: value2
}
Example
employee = {
"id": 101,
"name": "Alice",
"department": "IT"
}
print(employee)
Output
{'id': 101, 'name': 'Alice', 'department': 'IT'}
Creating a Dictionary with Different Data Types
Dictionary values can be of different data types.
Example
data = {
"name": "John",
"age": 25,
"salary": 50000.50,
"is_active": True
}
print(data)
Output
{'name': 'John', 'age': 25, 'salary': 50000.5, 'is_active': True}
Creating an Empty Dictionary
An empty dictionary can be created using curly braces.
Example
data = {}
print(data)
Output
{}
Creating an Empty Dictionary Using dict()
Example
data = dict()
print(data)
Output
{}
Creating a Dictionary Using dict()
The dict() function can also create dictionaries.
Example
student = dict(
name="John",
age=22,
course="Python"
)
print(student)
Output
{'name': 'John', 'age': 22, 'course': 'Python'}
Creating a Dictionary with Numeric Keys
Example
marks = {
1: "Math",
2: "Science",
3: "English"
}
print(marks)
Output
{1: 'Math', 2: 'Science', 3: 'English'}
Creating a Dictionary with Mixed Keys
Example
data = {
"name": "John",
101: "Employee ID",
True: "Active"
}
print(data)
Output
{'name': 'John', 101: 'Employee ID', True: 'Active'}
Dictionary Keys Must Be Unique
Duplicate keys are not allowed.
Example
student = {
"name": "John",
"name": "David"
}
print(student)
Output
{'name': 'David'}
The last value overwrites the previous value.
Creating a Nested Dictionary
A dictionary can contain another dictionary.
Example
student = {
"name": "John",
"marks": {
"Math": 90,
"Science": 85
}
}
print(student)
Output
{'name': 'John', 'marks': {'Math': 90, 'Science': 85}}
Creating a Dictionary from a List of Tuples
Example
data = [
("name", "John"),
("age", 25),
("city", "Delhi")
]
person = dict(data)
print(person)
Output
{'name': 'John', 'age': 25, 'city': 'Delhi'}
Creating a Dictionary Using User Input
Example
name = input("Enter name: ")
age = input("Enter age: ")
person = {
"name": name,
"age": age
}
print(person)
Sample Input
John
25
Output
{'name': 'John', 'age': '25'}
Dictionaries in Automation Testing
Dictionaries are heavily used in API testing and test data management.
Example: API Response Data
response = {
"status": 200,
"message": "Success"
}
print(response)
Output
{'status': 200, 'message': 'Success'}
Example: Store User Credentials
credentials = {
"username": "admin",
"password": "admin123"
}
print(credentials)
Output
{'username': 'admin', 'password': 'admin123'}
Example: Test Environment Configuration
environment = {
"browser": "Chrome",
"url": "https://example.com"
}
print(environment)
Output
{'browser': 'Chrome', 'url': 'https://example.com'}
Real-World Example: Employee Record
employee = {
"id": 101,
"name": "John",
"designation": "Developer"
}
print(employee)
Output
{'id': 101, 'name': 'John', 'designation': 'Developer'}
Real-World Example: Product Information
product = {
"name": "Laptop",
"price": 50000,
"stock": 20
}
print(product)
Output
{'name': 'Laptop', 'price': 50000, 'stock': 20}
Real-World Example: Student Details
student = {
"name": "Alice",
"grade": "A",
"marks": 95
}
print(student)
Output
{'name': 'Alice', 'grade': 'A', 'marks': 95}
Real-World Example: Website Configuration
config = {
"host": "localhost",
"port": 8080
}
print(config)
Output
{'host': 'localhost', 'port': 8080}
Checking Dictionary Type
Example
data = {
"name": "Python"
}
print(type(data))
Output
<class 'dict'>
Finding Dictionary Length
The len() function returns the number of key-value pairs.
Example
student = {
"name": "John",
"age": 25,
"city": "Delhi"
}
print(len(student))
Output
3
Common Mistakes Beginners Make
Using Duplicate Keys
Incorrect
data = {
"name": "John",
"name": "David"
}
Output
{'name': 'David'}
Only the last value is stored.
Forgetting Colons
Incorrect
student = {
"name" "John"
}
Error
SyntaxError
Correct
student = {
"name": "John"
}
Confusing Sets with Dictionaries
Example
data = {"Python", "Java"}
This creates a set, not a dictionary.
Best Practices
Use Meaningful Keys
employee = {
"employee_id": 101
}
Keep Key Names Consistent
user = {
"first_name": "John",
"last_name": "Doe"
}
Use Dictionaries for Related Data
student = {
"name": "John",
"marks": 90
}
Avoid Duplicate Keys
Each key should be unique.
Use Nested Dictionaries for Complex Data
employee = {
"address": {
"city": "Delhi"
}
}
Advantages of Dictionaries
Fast data retrieval
Easy data organization
Flexible key-value structure
Supports nested data
Widely used in APIs and databases
Efficient lookup operations
Limitations of Dictionaries
Keys must be unique
Keys must be immutable
Slightly higher memory usage than lists
Unordered in older Python versions
Conclusion
Dictionaries are one of the most versatile data structures in Python. They allow you to store and organize data using key-value pairs, making information easy to access and manage.
Whether you’re working with API responses, database records, application settings, or automation test data, dictionaries provide an efficient and readable way to handle structured information.
Understanding dictionary creation is essential before learning dictionary operations, methods, and advanced data processing techniques.
Frequently Asked Questions (FAQs)
What is a dictionary in Python?
A dictionary is a collection of key-value pairs.
Example:
student = {
"name": "John",
"age": 25
}
How do I create an empty dictionary?
data = {}
Output:
{}
Can dictionary keys be duplicated?
No.
Duplicate keys overwrite previous values.
data = {
"name": "John",
"name": "David"
}
Output:
{'name': 'David'}
Can dictionaries store different data types?
Yes.
data = {
"name": "John",
"age": 25,
"active": True
}
What is a nested dictionary?
A nested dictionary is a dictionary inside another dictionary.
student = {
"marks": {
"Math": 90
}
}
Key Takeaways
Dictionaries store data as key-value pairs.
Dictionaries are created using curly braces
{}ordict().Keys must be unique.
Values can be of any data type.
Dictionaries support nested structures.
Empty dictionaries can be created using
{}ordict().Dictionaries are widely used in automation testing and API handling.
The
len()function returns the number of key-value pairs.Meaningful keys improve code readability.
Understanding dictionary creation is essential before learning dictionary operations and methods.
