Python - Dictionaries

Hello, aspiring programmers! Today, we're going to dive into the fascinating world of Python dictionaries. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfy, and let's embark on this adventure together!

Python - Dictionaries

Dictionaries in Python

Imagine you're creating a digital address book. You want to store information about your friends, like their names, phone numbers, and email addresses. How would you do that? Enter Python dictionaries!

A dictionary in Python is like a real-world dictionary, but instead of word definitions, it stores key-value pairs. It's a collection that is unordered, changeable, and does not allow duplicates.

Key Features of Dictionaries

  1. Key-Value Pairs: Each item in a dictionary consists of a key and its corresponding value.
  2. Unordered: Unlike lists, dictionaries don't have a specific order.
  3. Changeable: You can add, remove, or modify items after the dictionary is created.
  4. No Duplicates: Each key must be unique within a dictionary.

Creating a Dictionary

Let's start by creating our first dictionary:

my_friend = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

In this example, we've created a dictionary called my_friend. The keys are "name", "age", and "city", and their corresponding values are "Alice", 25, and "New York".

You can also create an empty dictionary and add items later:

empty_dict = {}
another_dict = dict()  # Using the dict() constructor

Accessing Dictionary Items

To access items in a dictionary, you use the key names in square brackets:

print(my_friend["name"])  # Output: Alice

You can also use the get() method, which is safer because it returns None if the key doesn't exist (instead of raising an error):

print(my_friend.get("age"))  # Output: 25
print(my_friend.get("job"))  # Output: None

Modifying Dictionary Items

Dictionaries are mutable, meaning we can change their content after creation:

# Changing a value
my_friend["age"] = 26

# Adding a new key-value pair
my_friend["job"] = "Engineer"

print(my_friend)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}

Removing Dictionary Items

There are several ways to remove items from a dictionary:

# Remove a specific item
del my_friend["age"]

# Remove and return an item
job = my_friend.pop("job")

# Remove the last inserted item
last_item = my_friend.popitem()

print(my_friend)  # Output: {'name': 'Alice'}

Iterating Through a Dictionary

You can loop through a dictionary in several ways:

# Iterating through keys
for key in my_friend:
    print(key)

# Iterating through values
for value in my_friend.values():
    print(value)

# Iterating through both keys and values
for key, value in my_friend.items():
    print(f"{key}: {value}")

Properties of Dictionary Keys

Dictionary keys have some important properties:

  1. Keys must be immutable (like strings, numbers, or tuples).
  2. Keys must be unique within a dictionary.

For example:

valid_dict = {
    "string_key": "value1",
    42: "value2",
    (1, 2): "value3"
}

# This would raise an error:
# invalid_dict = {[1, 2]: "value"}  # Lists can't be keys

Python Dictionary Operators

Python provides some useful operators for dictionaries:

# Merging dictionaries (Python 3.5+)
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print(merged)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Checking if a key exists
if "name" in my_friend:
    print("Name is in the dictionary")

Python Dictionary Methods

Here's a table of commonly used dictionary methods:

Method Description
clear() Removes all items from the dictionary
copy() Returns a shallow copy of the dictionary
fromkeys() Creates a new dictionary with specified keys and value
get() Returns the value of the specified key
items() Returns a list of dictionary's (key, value) tuple pairs
keys() Returns a list of dictionary keys
pop() Removes and returns an element with the given key
popitem() Removes and returns the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

Built-in Functions with Dictionaries

Python provides several built-in functions that work well with dictionaries:

# Length of a dictionary
print(len(my_friend))

# Type of a dictionary
print(type(my_friend))

# Convert other data types to a dictionary
list_of_tuples = [("a", 1), ("b", 2)]
dict_from_list = dict(list_of_tuples)
print(dict_from_list)  # Output: {'a': 1, 'b': 2}

And there you have it, folks! We've journeyed through the land of Python dictionaries, from creation to manipulation, iteration to built-in functions. Remember, practice makes perfect, so don't be afraid to experiment with these concepts in your own code.

As we wrap up, let me share a little programming humor: Why do Python programmers prefer using dictionaries? Because they always know where their keys are! ?

Keep coding, stay curious, and remember: in the world of programming, every error is just a new learning opportunity. Until next time, happy coding!

Credits: Image by storyset