0% completed
A dictionary in Python is a data structure that stores key-value pairs, where each key is unique and maps to a corresponding value. This makes dictionaries ideal for fast data retrieval without relying on indexing positions like lists or tuples. Instead, data is accessed using keys, which act as identifiers.
Dictionaries are commonly used in data analysis, caching, configurations, and database-like storage where quick lookups are required. Unlike lists, dictionaries are unordered collections in Python versions before 3.7. However, starting from Python 3.7+, dictionaries maintain insertion order, meaning elements appear in the same order they were added.
Dictionaries also provide dynamic sizing, meaning they can grow or shrink as needed. The length of a dictionary can be determined using the len()
function, which returns the total number of key-value pairs.
A dictionary is created by placing key-value pairs inside curly braces {}
, where:
"Alice"
, "Bob"
, and "Eve"
are keys, while 22
, 25
, and 19
are their respective values.The number of key-value pairs in a dictionary can be determined using the len()
function.
len(student_ages)
returns 3
because the dictionary contains three key-value pairs.Dictionaries allow keys to be numbers or strings, while values can be of any type, including lists, tuples, or nested dictionaries.
"name"
and "age"
store string and integer values."hobbies"
stores a list as a value."married"
holds a boolean value."address"
contains a nested dictionary.Dictionaries are highly flexible, making them suitable for structured data storage.
Dictionary keys must be immutable, meaning they cannot be lists, other dictionaries, or any mutable object.
TypeError
because lists are mutable.Overall, Dictionaries provide efficient storage and retrieval of data, making them one of the most powerful built-in data structures in Python.
.....
.....
.....