Python Dictionary - Detailed Explanation
A dictionary in Python is a built-in data structure used to store
key-value pairs. It is mutable, meaning it can be changed after
creation.
Dictionaries are useful for fast lookups, organizing data, and
representing structured information.
Definition of Dictionary:
A dictionary is an unordered, mutable collection of elements where
each element is stored as a key-value pair. Keys must be unique and
immutable
(e.g., strings, numbers, tuples), while values can be of any data type.
Example of a Dictionary:
student = {
"name": "John",
"age": 20,
"course": "Computer Science"
}
print(student["name"]) # Output: John
Characteristics of Dictionary:
1. Unordered - Items are not stored in a specific sequence.
2. Mutable - You can modify values, add, or remove key-value pairs.
3. Keys are unique - No duplicate keys are allowed.
4. Keys must be immutable - Strings, numbers, and tuples can be
used as keys.
5. Fast Lookups - Dictionary lookup time is O(1) on average due to
hash tables.
Creating a Dictionary:
1. Using Curly Braces {}
person = {"name": "Alice", "age": 25, "city": "New York"}
2. Using the dict() Constructor
person = dict(name="Alice", age=25, city="New York")
3. Creating an Empty Dictionary
empty_dict = {}
Accessing Dictionary Elements:
1. Using Square Brackets []
print(person["name"]) # Output: Alice
2. Using the get() Method
print(person.get("age")) # Output: 25
print(person.get("gender", "Not specified")) # Output: Not specified
Modifying a Dictionary:
1. Updating a Value
person["age"] = 30
2. Adding a New Key-Value Pair
person["gender"] = "Female"
Removing Elements from a Dictionary:
1. Using del
del person["city"]
2. Using pop()
age = person.pop("age")
3. Using popitem()
pair = person.popitem()
4. Using clear()
person.clear()
Dictionary Methods:
keys(), values(), items(), update(), copy()
Looping Through a Dictionary:
for key, value in person.items():
print(f"{key}: {value}")
Nested Dictionaries:
students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
Applications of Dictionary:
1. Storing user data (e.g., name, age, email)
2. Counting occurrences of elements
3. Creating lookup tables
4. Storing JSON data
5. Representing graphs
Example: Counting Word Frequency:
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # Output: {'apple': 3, 'banana': 2, 'orange': 1}
Summary of Dictionary Features:
1. Stores Key-Value Pairs
2. Unordered
3. Mutable
4. Keys must be unique
5. Keys must be immutable
6. Fast Lookups
7. Built-in Methods
Final Definition:
"A dictionary in Python is an unordered, mutable data structure that
stores key-value pairs, allowing fast lookups, modifications,
and structured data representation."