Skip to main content

Working with Dictionaries and Sets

Dictionaries and sets are two of the most powerful, yet underutilized, data types in Python. They store items in a unique way that allows you to access data quickly and efficiently. If you're ready to take your Python skills to the next level, let's dive into how to work with dictionaries and sets in Python.

Introduction to Dictionaries

A dictionary in Python is an unordered collection of items. Each item stored in a dictionary has a key and value, making it similar to a real-life dictionary where each word (key) has a corresponding definition (value).

You can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. A colon : separates each key from its associated value.

# A simple dictionary
my_dict = {'name': 'John', 'age': 30}

Accessing Values in a Dictionary

To access a value in a dictionary, you refer to it by its key.

print(my_dict['name'])  # Output: John

Modifying a Dictionary

You can modify a dictionary by adding a new entry or a key-value pair, deleting an entry, or updating an existing entry.

# Adding an entry
my_dict['job'] = 'Engineer'
print(my_dict) # Output: {'name': 'John', 'age': 30, 'job': 'Engineer'}

# Updating an entry
my_dict['age'] = 31
print(my_dict) # Output: {'name': 'John', 'age': 31, 'job': 'Engineer'}

# Deleting an entry
del my_dict['job']
print(my_dict) # Output: {'name': 'John', 'age': 31}

Introduction to Sets

A set in Python is an unordered collection of unique items. They are useful when the existence of an item in a collection is more important than the item's order or how many times it occurs.

You can create a set by placing a comma-separated list of items inside curly braces {}.

# A simple set
my_set = {1, 2, 3, 4, 3, 2}
print(my_set) # Output: {1, 2, 3, 4}

Adding Items to a Set

You can add a single item to a set using the add() method, and multiple items using the update() method.

my_set.add(5)
print(my_set) # Output: {1, 2, 3, 4, 5}

my_set.update([6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}

Removing Items from a Set

You can remove an item from a set using the remove() or discard() method. The remove() method will raise an error if the item is not found, while discard() will not.

my_set.remove(7)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

my_set.discard(6)
print(my_set) # Output: {1, 2, 3, 4, 5}

Dictionaries and sets are powerful tools that can significantly enhance your data manipulation capabilities in Python. They are particularly useful when you need to store unique items, or map keys to values, and can lead to more efficient, readable, and manageable code. Practice working with these data types to become more comfortable with them and understand their potential.