Dictionaries are a fundamental data structure in Python that allow you to store and manage key-value pairs. They are highly efficient for retrieving data, making them indispensable for various applications such as configuration settings, caches, and more. In this tutorial, we'll explore how to create dictionaries, access their values, modify them, and use some of the built-in methods they provide.
Dictionaries in Python are similar to associative arrays or hash tables in other programming languages. They consist of a collection of key-value pairs where each key is unique. Dictionaries are mutable, meaning you can add, update, or remove items after their creation. This flexibility makes them versatile and powerful for various data manipulation tasks.
You can create a dictionary using curly braces {} with key-value pairs separated by colons :. Alternatively, you can use the dict() constructor.
1# Creating a dictionary using curly braces2person = {3"name": "Alice",4"age": 30,5"city": "New York"6}
You can access values in a dictionary using their corresponding keys. If you try to access a key that doesn't exist, Python will raise a KeyError.
1# Accessing values by key2name = person["name"]3age = person.get("age")
You can add new key-value pairs to a dictionary or update existing ones by assigning values to keys.
1# Adding a new key-value pair2person["occupation"] = "Engineer"34# Updating an existing key5person["age"] = 31
The pop() method removes the key and returns its value. If the key doesn't exist, it raises a KeyError, unless you provide a default value.
1# Removing a key-value pair using pop()2age = person.pop("age")
The setdefault() method returns the value of a key if it exists in the dictionary. If not, it inserts the key with a specified default value and returns that value.
1# Using setdefault()2person.setdefault("city", "Los Angeles")
Dictionary comprehensions provide a concise way to create dictionaries. They are similar to list comprehensions but use curly braces {}.
1# Creating a dictionary using a comprehension2squares = {x: x**2 for x in range(5)}
{} or dict().[] or the get() method.del statement or pop() method.keys(), values(), items(), setdefault(), and update().In the next tutorial, we'll explore Python sets, another essential data structure. Sets are unordered collections of unique elements that are useful for membership testing, removing duplicates from sequences, and performing mathematical set operations like unions, intersections, and differences. Stay tuned!