Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Understanding Dictionaries in Python

Learn the ins and outs of dictionaries, a fundamental data structure in Python. …


Updated June 13, 2023

Learn the ins and outs of dictionaries, a fundamental data structure in Python. Dictionaries and Dictionary Operations

What are Dictionaries?

In Python, a dictionary is an unordered collection of key-value pairs. It’s a mutable data type that allows you to store and manipulate data in a structured way. Dictionaries are also known as associative arrays or hash tables in other programming languages.

Defining a Dictionary

A dictionary is defined using the dict keyword in Python, followed by a set of key-value pairs inside curly brackets {}. Each key is unique and maps to a specific value.

# Define a dictionary with three key-value pairs
person = {"name": "John", "age": 30, "city": "New York"}

Accessing Dictionary Values

You can access a dictionary’s values using the key as an index. If the key exists in the dictionary, it returns the corresponding value.

# Access the person's name and age
print(person["name"])  # Output: John
print(person["age"])   # Output: 30

Modifying Dictionary Values

You can modify a dictionary’s values by assigning a new value to an existing key.

# Update the person's city
person["city"] = "Los Angeles"
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'Los Angeles'}

Adding New Key-Value Pairs

You can add new key-value pairs to a dictionary using the assignment operator.

# Add an email address to the person's dictionary
person["email"] = "john@example.com"
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'Los Angeles', 'email': 'john@example.com'}

Removing Key-Value Pairs

You can remove a key-value pair from a dictionary using the del keyword.

# Remove the person's email address
del person["email"]
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'Los Angeles'}

Dictionary Methods

Dictionaries have several built-in methods that allow you to perform various operations. Here are a few examples:

  • keys(): Returns a view object that displays a list of all the keys in the dictionary.
  • values(): Returns a view object that displays a list of all the values in the dictionary.
  • items(): Returns a view object that displays a list of all key-value pairs in the dictionary.
# Get the person's keys, values, and items
print(person.keys())  # Output: dict_keys(['name', 'age', 'city'])
print(person.values())  # Output: dict_values(['John', 30, 'Los Angeles'])
print(person.items())  # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'Los Angeles')])

Dictionary Operations

Dictionaries support various operations such as union, intersection, and difference. Here are a few examples:

  • dict1 | dict2: Returns a new dictionary containing all key-value pairs from both dictionaries.
  • dict1 & dict2: Returns a new dictionary containing only the key-value pairs common to both dictionaries.
  • dict1 - dict2: Returns a new dictionary containing only the key-value pairs not present in the second dictionary.
# Perform union, intersection, and difference operations on two dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

print(dict1 | dict2)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dict1 & dict2)  # Output: {}
print(dict1 - dict2)  # Output: {'a': 1, 'b': 2}

Conclusion

In this article, we’ve covered the basics of dictionaries in Python, including how to define them, access their values, modify them, and perform various operations. We’ve also touched on dictionary methods and operations, which are essential for working with these data structures. With practice and experience, you’ll become proficient in using dictionaries to solve complex problems in Python programming.

Next Steps

If you’re new to Python programming, we recommend starting with the basics of variables, data types, and operators. Once you have a solid grasp of these concepts, move on to more advanced topics such as functions, loops, and control structures. From there, you can dive deeper into object-oriented programming, file input/output, and other essential areas.

Resources

For further learning, we recommend the following resources:

  • Python documentation: The official Python documentation is an exhaustive resource that covers every aspect of the language.
  • W3Schools: W3Schools offers a comprehensive tutorial on Python basics, including variables, data types, operators, and more.
  • Codecademy: Codecademy provides interactive coding lessons and exercises to help you practice your skills.

By following these resources and practicing regularly, you’ll become proficient in using dictionaries and other data structures in Python programming. Happy learning!

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp