DEV Community

Cover image for Start with Python Dictionaries
Shaheryar
Shaheryar

Posted on

Start with Python Dictionaries

Python dictionaries are powerful data structures that allow you to store and manipulate collections of key-value pairs. Understanding dictionaries and their usage is crucial for effective Python programming.

What are Python Dictionaries?

Dictionaries in Python are unordered collections of items, where each item consists of a key-value pair. Dictionaries are mutable, meaning they can be modified after creation. Dictionaries are often used to represent mappings between unique keys and their corresponding values.

Creating Dictionaries

Dictionaries are created by enclosing key-value pairs in curly braces { }, separated by commas, with a colon : separating each key and its corresponding value.

# Example of creating a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

You can access the value associated with a specific key in a dictionary by using square brackets and the key itself.

# Example of accessing elements
print(my_dict["name"])   # Output: Alice
print(my_dict["age"])    # Output: 30
Enter fullscreen mode Exit fullscreen mode

Modifying Dictionaries

Dictionaries can be modified by adding, removing, or updating key-value pairs.

# Example of modifying a dictionary
my_dict["email"] = "alice@example.com"    # Add a new key-value pair
my_dict["age"] = 31                        # Update the value associated with a key
del my_dict["city"]                        # Remove a key-value pair
Enter fullscreen mode Exit fullscreen mode

Dictionary Methods

Python dictionaries provide several built-in methods for working with dictionaries, such as keys(), values(), items(), get(), pop(), and update().

# Example of dictionary methods
print(my_dict.keys())      # Output: dict_keys(['name', 'age', 'email'])
print(my_dict.values())    # Output: dict_values(['Alice', 31, 'alice@example.com'])
print(my_dict.items())     # Output: dict_items([('name', 'Alice'), ('age', 31), ('email', 'alice@example.com')])
Enter fullscreen mode Exit fullscreen mode

Use Cases

Dictionaries are commonly used for:

  • Storing settings and configurations.
  • Representing JSON data.
  • Counting occurrences of items in a collection.

Handling Missing Keys

The get() method allows you to retrieve the value associated with a key, with an optional default value to return if the key is not found.

# Example of handling missing keys
print(my_dict.get("gender", "Unknown"))   # Output: Unknown (since "gender" key does not exist)
Enter fullscreen mode Exit fullscreen mode

Python dictionaries are versatile data structures that offer efficient key-based lookup and manipulation. By understanding how to create, access, and utilize dictionaries, you can write more efficient and expressive code. Dictionaries are a fundamental tool in Python programming, allowing you to represent mappings between keys and values in a clear and concise manner.

Top comments (0)