DEV Community

Cover image for How Python Dictionaries Keep Your Code Clean and DRY
Ashwin Kumar
Ashwin Kumar

Posted on

How Python Dictionaries Keep Your Code Clean and DRY

Python Dictionary and the DRY Principle: A Quick Guide for Beginners

Hey there! šŸ‘‹ If youā€™re diving into Python programming, youā€™ve probably stumbled upon dictionaries and maybe wondered, ā€œWhat exactly is a dictionary in Python, and how can it help me code smarter?ā€ No worries letā€™s break it down in a super simple way.

Whatā€™s a Dictionary in Python?

Imagine you have a list of items, and each item has a unique label attached to it, like ā€œname: Johnā€ or ā€œage: 25ā€. A dictionary in Python works exactly like that! Itā€™s a collection of key value pairs, where each key is unique and points to a specific value. Think of it as a mini database for storing information in a neat and organized way.

Itā€™s like a real dictionary where you look up a word (the key) and get its meaning (the value). Cool, right? šŸ˜Ž

How to Make a Dictionary in Python?

Creating a dictionary is as easy as pie. You just use curly braces {} and separate each key value pair with a colon :.

Hereā€™s how you can make a simple dictionary:

# Creating a dictionary to store student information
student_info = {
    'name': 'John Doe',
    'age': 21,
    'major': 'Computer Science'
}

# Printing out the dictionary
print(student_info)
Enter fullscreen mode Exit fullscreen mode

This dictionary stores a studentā€™s name, age, and major. Notice how the keys like 'name' and 'age' are in quotes? Thatā€™s because keys can be strings, numbers, or even tuples! The values can be anything strings, lists, other dictionaries, you name it.

How Dictionaries Help Us to Avoid Repetition (DRY Principle)

Now, hereā€™s where it gets interesting. You may have heard of the DRY principle, which stands for Donā€™t Repeat Yourself. Itā€™s a rule that encourages you to avoid redundancy in your code. How can dictionaries help with that? Letā€™s take a look.

Before Using a Dictionary (Repeating Code)

Imagine you want to store information about students in separate variables. It might look something like this:

student1_name = 'Alice'
student1_age = 20
student1_major = 'Mathematics'

student2_name = 'Bob'
student2_age = 22
student2_major = 'Physics'
Enter fullscreen mode Exit fullscreen mode

Not only do we have repetitive variable names, but if we want to print or update these, we have to repeat ourselves again and again. This is where dictionaries can save the day! šŸ¦ø

Example 1: After Using a Dictionary (DRY Version)

With dictionaries, we can store all this information in a cleaner way:

# Using dictionaries to store student data
students = {
    'student1': {'name': 'Alice', 'age': 20, 'major': 'Mathematics'},
    'student2': {'name': 'Bob', 'age': 22, 'major': 'Physics'}
}

print(students['student1']['name'])  # Output: Alice
print(students['student2']['age'])   # Output: 22
Enter fullscreen mode Exit fullscreen mode

Now, you donā€™t have to create separate variables for each studentā€™s name, age, and major. You can access or update the information in a much simpler way. Plus, it makes your code cleaner and easier to manage.

Example 2: Avoiding Repetition with Dictionaries

Letā€™s say you want to create a simple grading system based on student scores. Without dictionaries, you might end up writing the following:

# Without dictionary (repeating code)
alice_score = 90
bob_score = 75
charlie_score = 85

if alice_score >= 85:
    print("Alice gets an A")
if bob_score >= 85:
    print("Bob gets an A")
if charlie_score >= 85:
    print("Charlie gets an A")
Enter fullscreen mode Exit fullscreen mode

Here, weā€™re repeating the if statements and hardcoding each studentā€™s name and score, which violates the DRY principle.

Instead, with a dictionary, you can avoid repetition like this:

# Using a dictionary (DRY principle)
student_scores = {'Alice': 90, 'Bob': 75, 'Charlie': 85}

for student, score in student_scores.items():
    if score >= 85:
        print(f"{student} gets an A")
Enter fullscreen mode Exit fullscreen mode

Now, you have a cleaner, shorter, and more maintainable code! You only write the if statement once, and it works for all students in your dictionary. šŸŽ‰

Useful Dictionary Methods

Dictionaries come with a bunch of built-in methods that make working with them a breeze. Letā€™s check out a few of them:

  1. .get(): Helps you avoid errors if the key doesnā€™t exist.
   print(student_info.get('address', 'Address not available'))  
   # Output: Address not available
Enter fullscreen mode Exit fullscreen mode
  1. .keys() and .values(): Get all keys or values in the dictionary.
   print(student_info.keys())  # Output: dict_keys(['name', 'age', 'major'])
   print(student_info.values())  # Output: dict_values(['John Doe', 21, 'Computer Science'])
Enter fullscreen mode Exit fullscreen mode
  1. .items(): Get both keys and values as pairs.
   for key, value in student_info.items():
       print(f'{key}: {value}')
   # Output: 
   # name: John Doe
   # age: 21
   # major: Computer Science
Enter fullscreen mode Exit fullscreen mode
  1. .update(): Update a dictionary with another dictionary or key-value pairs.
   student_info.update({'grade': 'A'})
   print(student_info)  
   # Output: {'name': 'John Doe', 'age': 21, 'major': 'Computer Science', 'grade': 'A'}
Enter fullscreen mode Exit fullscreen mode
  1. .setdefault(): Adds a key with a default value if the key doesnā€™t exist.
   student_info.setdefault('graduation_year', 2024)
   print(student_info)  
   # Output: {'name': 'John Doe', 'age': 21, 'major': 'Computer Science', 'grade': 'A', 'graduation_year': 2024}
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

Dictionaries are super powerful and can really help you follow the DRY principle in your code. By using dictionaries, you avoid repeating yourself, keep your code organized, and make it easier to read and maintain.

So, the next time you find yourself creating a bunch of similar variables, consider using a dictionary instead. Itā€™ll save you a ton of time and effort, and your future self will thank you! šŸ™Œ

Happy coding! šŸ’»

Top comments (0)