This content originally appeared on DEV Community and was authored by DevOps Fundamental
Understanding Dictionaries for Beginners
Dictionaries are a fundamental data structure in many programming languages, and understanding them is a huge step towards becoming a more confident programmer! They’re incredibly useful for storing and retrieving information, and you’ll encounter them everywhere – from simple address books to complex data analysis. You’ll likely be asked about dictionaries in technical interviews too, so getting a good grasp of them now will really pay off.
Understanding Dictionaries
Imagine a real-world dictionary. You look up a word (the key) and it gives you a definition (the value). Programming dictionaries work the same way! They store data in key-value pairs.
Think of it like this: you have a box (the dictionary). Inside the box, you put labeled containers. The label is the key, and what’s inside the container is the value. You use the label to find what you need.
Unlike lists, which access items by their position (index), dictionaries access items by their key. This makes them super efficient for looking up specific information.
Here’s a visual representation using a Mermaid diagram:
graph LR
A[Dictionary] --> B(Key 1: Value 1)
A --> C(Key 2: Value 2)
A --> D(Key 3: Value 3)
In this diagram, ‘A’ is the dictionary, and ‘B’, ‘C’, and ‘D’ are the key-value pairs stored within it.
Basic Code Example
Let’s look at how to create and use a dictionary in Python:
# Creating a dictionary to store information about a person
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values using keys
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
# Adding a new key-value pair
person["occupation"] = "Engineer"
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
# Modifying an existing value
person["age"] = 31
print(person) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
Let’s break down what’s happening:
-
person = { ... }
creates a new dictionary namedperson
. - Inside the curly braces
{}
, we define key-value pairs separated by commas. - Each key-value pair consists of a
key: value
. Keys and values are separated by a colon:
. -
print(person["name"])
accesses the value associated with the key “name”. We use square brackets[]
to access values. -
person["occupation"] = "Engineer"
adds a new key-value pair to the dictionary. -
person["age"] = 31
updates the value associated with the key “age”.
Now, let’s look at a JavaScript example:
// Creating a dictionary (object) to store information about a person
const person = {
name: "Bob",
age: 25,
city: "London"
};
// Accessing values using keys
console.log(person.name); // Output: Bob
console.log(person.age); // Output: 25
// Adding a new key-value pair
person.occupation = "Teacher";
console.log(person); // Output: { name: 'Bob', age: 25, city: 'London', occupation: 'Teacher' }
// Modifying an existing value
person.age = 26;
console.log(person); // Output: { name: 'Bob', age: 26, city: 'London', occupation: 'Teacher' }
The JavaScript example is very similar. Instead of curly braces, we use {}
to define the object (which acts as our dictionary). We access values using dot notation (person.name
) instead of square brackets.
Common Mistakes or Misunderstandings
Let’s look at some common pitfalls when working with dictionaries:
Incorrect code (Python):
person = {"name": "Charlie"}
print(person["address"]) # This will cause an error!
Corrected code (Python):
person = {"name": "Charlie"}
# Check if the key exists before accessing it
if "address" in person:
print(person["address"])
else:
print("Address not found")
Explanation: Trying to access a key that doesn’t exist in the dictionary will raise a KeyError
. Always check if a key exists before trying to access its value using the in
operator.
Incorrect code (JavaScript):
const person = { name: "David" };
console.log(person.phone); // This will output undefined
Corrected code (JavaScript):
const person = { name: "David" };
// Check if the key exists before accessing it
if (person.hasOwnProperty("phone")) {
console.log(person.phone);
} else {
console.log("Phone number not found");
}
Explanation: In JavaScript, accessing a non-existent key returns undefined
. While it doesn’t throw an error, it’s good practice to check if the key exists using hasOwnProperty()
to avoid unexpected behavior.
Incorrect code (Both Languages):
# Python
my_dict = {1: "one", 1: "two"} # Last value for key 1 will be kept
# JavaScript
const myDict = {1: "one", 1: "two"}; // Last value for key 1 will be kept
Corrected code (Both Languages):
Dictionaries only allow unique keys. If you try to use the same key multiple times, the last value assigned to that key will be the one that’s stored.
Real-World Use Case: Simple Inventory System
Let’s create a simple inventory system for a store.
inventory = {
"apples": 10,
"bananas": 5,
"oranges": 15
}
def update_inventory(item, quantity):
if item in inventory:
inventory[item] += quantity
else:
inventory[item] = quantity
def get_inventory_count(item):
if item in inventory:
return inventory[item]
else:
return 0
# Add 3 apples to the inventory
update_inventory("apples", 3)
print(inventory) # Output: {'apples': 13, 'bananas': 5, 'oranges': 15}
# Check how many bananas are in stock
print(get_inventory_count("bananas")) # Output: 5
# Check how many pears are in stock
print(get_inventory_count("pears")) # Output: 0
This example demonstrates how dictionaries can be used to store and manage data in a real-world scenario. We use functions to encapsulate the logic for updating and retrieving inventory counts, making the code more organized and reusable.
Practice Ideas
Here are a few ideas to practice your dictionary skills:
- Phonebook: Create a dictionary to store names and phone numbers. Allow the user to add, search, and delete entries.
- Word Counter: Read a text file and count the frequency of each word using a dictionary.
- Student Grades: Store student names and their grades in a dictionary. Calculate the average grade for each student.
- Simple Shopping Cart: Create a dictionary to represent a shopping cart, where keys are item names and values are quantities.
- Character Frequency: Given a string, create a dictionary that stores the frequency of each character in the string.
Summary
Congratulations! You’ve taken your first steps towards mastering dictionaries. You’ve learned what they are, how to create and use them, common mistakes to avoid, and how they can be applied to solve real-world problems.
Dictionaries are a powerful tool in any programmer’s arsenal. Keep practicing, and don’t be afraid to experiment. Next, you might want to explore more advanced dictionary methods (like .keys()
, .values()
, and .items()
) or learn about dictionary comprehensions for creating dictionaries in a concise way. Happy coding!
This content originally appeared on DEV Community and was authored by DevOps Fundamental