Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In Python, a dictionary is a versatile and widely used data structure that stores a collection of key-value pairs. Dictionaries
are also known as associative arrays or hash maps in other programming languages. Unlike lists or tuples, which are ordered sequences, dictionaries
are unordered, and their elements are accessed by keys rather than by indices.
Here are some key characteristics and operations associated with dictionaries:
You can create a dictionary
by enclosing a comma-separated sequence of key-value pairs within curly braces {}
. Each key-value pair is separated by a colon. For example:
pythonmy_dict = {"name": "Alice", "age": 30, "city": "New York"}
To access a value in a dictionary
, you use its associated key within square brackets []
or with the get()
method:
pythonname = my_dict["name"]
age = my_dict.get("age")
If the key is not found, using [] will raise a KeyError
, whereas get()
will return None (or a specified default value) without raising an error.
Dictionaries
are mutable, which means you can add, modify, or delete key-value pairs:
Adding a new key-value pair:
pythonmy_dict["country"] = "USA"
Modifying an existing value:
pythonmy_dict["age"] = 31
Deleting a key-value pair:
pythondel my_dict["city"]
Python dictionaries
provide various built-in methods for common dictionary operations, such as keys()
, values()
, and items()
for accessing keys, values, and key-value pairs, respectively:
pythonkeys = my_dict.keys() # Returns a list of keys
values = my_dict.values() # Returns a list of values
items = my_dict.items() # Returns a list of key-value pairs
You can use the in keyword to check if a key exists in a dictionary
:
pythonif "name" in my_dict:
print("Name is in the dictionary.")
Similar to list comprehensions, Python also supports dictionary comprehensions, which allow you to create dictionaries
in a concise manner:
pythonnumbers = [1, 2, 3, 4, 5]
squares_dict = {x: x**2 for x in numbers}
Dictionaries
can be nested inside other dictionaries to represent complex data structures:
pythonstudent = {
"name": "Alice",
"grades": {"math": 95, "science": 88, "history": 92}
}
You can use the get()
method with a default value to retrieve a value for a key, providing a default value if the key doesn't exist:
Dictionaries
are commonly used in Python to store and manipulate data in a structured way, particularly when you need to associate values with unique keys. They are suitable for a wide range of applications, from configuration settings to database-like data retrieval. The ability to efficiently access values by key makes dictionaries a powerful and versatile data structure in Python.