A dictionary in Python is a built-in data type that allows you to store data in key-value pairs. Unlike sequences such as lists or tuples, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type (such as strings, numbers, or tuples). This makes dictionaries highly flexible and ideal for situations where you want to associate a unique key with a value.
Dictionaries can be created using curly braces {}
with key-value pairs separated by a colon :
. Alternatively, you can use the dict()
function.
Example:
To access a value in a dictionary, you use the key associated with that value. If the key is not found, Python will raise a KeyError
. To avoid this, you can use the get()
method, which returns None
or a default value if the key is not found.
Example:
You can add a new key-value pair or modify an existing value by assigning a value to a key.
Example:
You can remove items from a dictionary using several methods:
del
: Deletes a key-value pair by key.pop():
Removes a key-value pair by key and returns the value.popitem()
: Removes the last inserted key-value pair and returns it (in Python 3.7+).clear()
: Removes all key-value pairs from the dictionary.Example:
Python dictionaries come with a variety of built-in methods that make it easy to manipulate the data they store:
keys()
: Returns a view object of all keys.values()
: Returns a view object of all values.items()
: Returns a view object of all key-value pairs.update()
: Updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs.Example:
You can iterate over dictionaries using loops to access keys, values, or both.
Example:
Dictionaries can contain other dictionaries, making it possible to create nested structures.
Example:
Example:
dict
as a Variable Name: dict
is a built-in function and should not be used as a variable name to avoid confusion.KeyError
.get()
for Safe Access: Use get()
to access dictionary values safely.Dictionaries in Python are powerful and versatile tools for managing data. By understanding how to create, manipulate, and use dictionaries effectively, you can write more efficient and readable Python code. Whether you're counting frequencies, storing configuration settings, or working with JSON-like data structures, dictionaries are a go-to choice for many common programming tasks.