Introduction to Dictionaries in Python

In Python, a dictionary is a powerful data structure that allows you to store and retrieve data in key-value pairs. It is often used when you want to associate some information (the value) with a unique identifier (the key). Think of a dictionary as a real-life dictionary where you look up a word (the key) to find its corresponding definition (the value).

Dictionaries are incredibly versatile and can be used to solve a wide range of problems in Python. In this webpage, we will cover everything you need to know about dictionaries, from creating them to manipulating their contents.

Let’s dive in!

What is a Dictionary?

A dictionary in Python is an unordered collection of key-value pairs. Each key is unique within a dictionary, and it is used to access its corresponding value. Dictionaries are enclosed in curly braces {} and consist of comma-separated key-value pairs.

For example, let’s say we want to create a dictionary to store the prices of different fruits:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

In this dictionary, the fruit names (e.g., “apple”, “banana”, “orange”) are the keys, and the prices (e.g., 0.99, 0.75, 1.25) are the corresponding values.

Creating a Dictionary

To create a dictionary, you can define it directly or use the dict() constructor. Here’s an example of both methods:

Method 1: Using curly braces

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

Method 2: Using the dict() constructor

fruits_prices = dict(apple=0.99, banana=0.75, orange=1.25)

Accessing Values in a Dictionary

To access a value in a dictionary, you need to provide its corresponding key. You can do this by using square brackets [] or the get() method.

Here’s an example:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

Accessing values using square brackets

print(fruits_prices[“apple”]) # Output: 0.99

Accessing values using the get() method

print(fruits_prices.get(“banana”)) # Output: 0.75

Both methods will give you the value associated with the specified key.

Modifying Values in a Dictionary

Dictionaries are mutable, which means you can modify the values they contain. To update the value of a specific key, simply assign a new value to it.

Here’s an example:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

fruits_prices[“apple”] = 1.29 # Updating the value of the “apple” key

print(fruits_prices[“apple”]) # Output: 1.29

In this example, we modified the price of an apple from 0.99 to 1.29.

Adding and Removing Key-Value Pairs

You can add new key-value pairs to a dictionary or remove existing ones using various methods.

To add a new key-value pair, simply assign a value to a new key:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

fruits_prices[“kiwi”] = 1.99 # Adding a new key-value pair

print(fruits_prices)

Output

{
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25,
“kiwi”: 1.99
}

To remove a key-value pair, you can use the del keyword or the pop() method:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

del fruits_prices[“banana”] # Removing a key-value pair using del

print(fruits_prices)

removed_price = fruits_prices.pop(“orange”) # Removing a key-value pair using pop
print(fruits_prices)
print(removed_price)

Output

{
“apple”: 0.99,
“orange”: 1.25
}
{
“apple”: 0.99
}
1.25

Dictionary Methods

Python dictionaries provide several useful methods to perform various operations. Here are a few commonly used methods:

  • keys(): Returns a list of all the keys in the dictionary.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list of tuples containing key-value pairs.
  • clear(): Removes all the key-value pairs from the dictionary.
  • copy(): Returns a shallow copy of the dictionary.

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

print(fruits_prices.keys()) # Output: [“apple”, “banana”, “orange”]
print(fruits_prices.values()) # Output: [0.99, 0.75, 1.25]
print(fruits_prices.items()) # Output: [(“apple”, 0.99), (“banana”, 0.75), (“orange”, 1.25)]

fruits_prices.clear() # Clears all the key-value pairs from the dictionary

print(fruits_prices) # Output: {}

Looping Through a Dictionary

You can iterate over a dictionary to access its keys, values, or both using a loop. Here’s an example:

fruits_prices = {
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

Looping through keys

for fruit in fruits_prices:
print(fruit)

Looping through values

for price in fruits_prices.values():
print(price)

Looping through both keys and values

for fruit, price in fruits_prices.items():
print(f”{fruit}: {price}”)

Dictionary Comprehension

Similar to list comprehension, Python also allows you to create dictionaries using dictionary comprehension. It provides a concise way to create dictionaries based on existing iterables.

Here’s an example of creating a dictionary using dictionary comprehension:

fruits = [“apple”, “banana”, “orange”]
prices = [0.99, 0.75, 1.25]

fruits_prices = {fruit: price for fruit, price in zip(fruits, prices)}

print(fruits_prices)

Output

{
“apple”: 0.99,
“banana”: 0.75,
“orange”: 1.25
}

Nested Dictionaries

Dictionaries can also be nested, which means you can have dictionaries as values within another dictionary. This allows you to represent more complex data structures.

Here’s an example of a nested dictionary:

student = {
“name”: “John Doe”,
“age”: 20,
“grades”: {
“math”: 90,
“science”: 85,
“english”: 92
}
}

print(student[“grades”][“math”]) # Output: 90

In this example, the student dictionary contains another dictionary called grades, which stores the grades for different subjects.

Conclusion

Dictionaries are an essential part of Python programming. They provide a flexible and efficient way to store and retrieve data using key-value pairs. By understanding the basics of dictionaries, you can solve a wide range of problems and manipulate data effectively in Python.

We covered creating dictionaries, accessing and modifying values, adding and removing key-value pairs, dictionary methods, looping through dictionaries, dictionary comprehension, and nested dictionaries.

Keep practicing and exploring dictionaries in Python, and you’ll become more comfortable using this powerful data structure. Happy coding!