Python Dictionaries

Welcome to The Coding College, where programming concepts become accessible to everyone! Today, we’re diving into Python Dictionaries, one of the most versatile and commonly used data structures in Python.

What Is a Python Dictionary?

A dictionary in Python is a collection of key-value pairs. Each key in a dictionary is unique and acts as an identifier for its corresponding value.

Key Features of Dictionaries:

  • Unordered: Items in a dictionary are not stored in a specific order (though Python 3.7+ maintains insertion order).
  • Changeable: You can add, update, or remove key-value pairs.
  • Indexed by Keys: Access values using unique keys.
  • No Duplicate Keys: Each key must be unique, but values can be repeated.

Why Use Dictionaries?

Dictionaries are ideal when you need to:

  1. Quickly retrieve data using keys.
  2. Store related data in a structured way (e.g., user profiles, configurations).
  3. Avoid duplicate keys while still allowing duplicate values.

How to Create a Dictionary

Creating a dictionary is simple:

# Empty dictionary  
my_dict = {}  

# Dictionary with data  
person = {  
    "name": "Alice",  
    "age": 25,  
    "city": "New York"  
}  
print(person)  

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York'}  

Accessing Dictionary Items

You can access dictionary values using their keys.

Example:

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

# Accessing a value  
print(person["name"])  # Output: Alice  

# Using the `get()` method  
print(person.get("age"))  # Output: 25  

Adding or Updating Items

You can add new key-value pairs or update existing ones.

Example:

person = {"name": "Alice", "age": 25}  

# Adding a new item  
person["city"] = "New York"  

# Updating an existing item  
person["age"] = 26  

print(person)  

Output:

{'name': 'Alice', 'age': 26, 'city': 'New York'}  

Removing Items

You can remove items using methods like pop() or del.

Example:

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

# Remove a specific item  
person.pop("age")  

# Remove an item using `del`  
del person["city"]  

print(person)  

Output:

{'name': 'Alice'}  

Looping Through Dictionaries

You can loop through keys, values, or both.

Example:

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

# Loop through keys  
for key in person:  
    print(key)  

# Loop through values  
for value in person.values():  
    print(value)  

# Loop through key-value pairs  
for key, value in person.items():  
    print(f"{key}: {value}")  

Output:

name  
age  
city  
Alice  
25  
New York  
name: Alice  
age: 25  
city: New York  

Dictionary Methods

Here are some commonly used dictionary methods:

MethodDescriptionExample
get(key)Returns the value for the specified keyperson.get("name")'Alice'
keys()Returns a list of all keysperson.keys()dict_keys(['name', ...])
values()Returns a list of all valuesperson.values()dict_values([...])
items()Returns a list of key-value pairsperson.items()dict_items([...])
pop(key)Removes the specified key and returns its valueperson.pop("age")25
update(other_dict)Updates the dictionary with another dictionaryperson.update({"country": "USA"})

Dictionary Use Cases

  • Storing Structured Data:
user_profile = {  
    "username": "coder123",  
    "email": "[email protected]",  
    "languages": ["Python", "JavaScript"]  
}  
  • Counting Frequency:
from collections import Counter  

words = ["apple", "banana", "apple", "orange", "banana"]  
word_count = Counter(words)  
print(word_count)  
  • Output:
{'apple': 2, 'banana': 2, 'orange': 1}  
  • Mapping Unique Identifiers to Data:
student_scores = {  
    101: "A",  
    102: "B",  
    103: "A"  
}  
print(student_scores[101])  # Output: A  

Practice Exercises

Exercise 1: Create and Access a Dictionary

Create a dictionary with your name, age, and favorite programming language. Access the values using keys.

Exercise 2: Update a Dictionary

Given a dictionary with {1: "one", 2: "two"}, add the key-value pair 3: "three".

Exercise 3: Remove an Item

Remove the key age from the dictionary {"name": "Alice", "age": 25, "city": "New York"}.

Why Learn Dictionaries with The Coding College?

At The Coding College, we emphasize practical knowledge and hands-on learning. Mastering dictionaries will enable you to efficiently manage structured data, a critical skill for real-world programming.

Conclusion

Python dictionaries are incredibly powerful for organizing and manipulating data. From storing user profiles to counting word frequencies, they offer unparalleled flexibility and efficiency.

Leave a Comment