Python_Dictionary
Python_Dictionary
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"}
Modifying a Dictionary:
1. Updating a Value
person["age"] = 30
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()
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
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."