Python Best Practice: Dictionary Operation

Photo by Syd Wachs on Unsplash

Python Best Practice: Dictionary Operation

Introduction of list to dictionary, dictionary "get" method and Counter class in Python

ยท

2 min read

1. Introduction

This blog introduces some best practices of handling dictionary in Python.

2. List to Dictionary

Sometimes, you may need to convert list into dictionary by treating each element in the list as key and assign them with the same value. This can be done by list comprehension.

student = ["James", "Abhinay", "Peter", "Bicky"]

student_2_is_present_dict = { stu : False for stu in student }

print(f'{ student_2_is_present_dict= }')
# student_2_is_present_dict= {'James': False, 'Abhinay': False, 'Peter': False, 'Bicky': False}

3. Get method for no key value in dictionary

Key is used to get value from dictionary, but what's happen if the key does not exists? ๐Ÿค”

student_arr = ["James", "Bicky", "Abhinay", "Peter", "Bicky", "Amy"]

stu_2_count_dict = {}
for student in student_arr:
    stu_2_count_dict[ student ] += 1

print(f'{ stu_2_count_dict= }')
# KeyError: 'James'

In the above example, we saw that KeyError occurs if the specific key is not found in the dictionary stu_2_count_dict.

We modify the code as follow to fix the error.

student_arr = ["James", "Bicky", "Abhinay", "Peter", "Bicky", "Amy"]

stu_2_count_dict = {}
for student in student_arr:
    if not student in stu_2_count_dict:
        stu_2_count_dict[ student ] = 1
    else:
        stu_2_count_dict[ student ] = stu_2_count_dict[student] + 1

print(f'{ stu_2_count_dict= }')
# stu_2_count_dict= {'James': 1, 'Bicky': 2, 'Abhinay': 1, 'Peter': 1, 'Amy': 1}

The if statement here will quite clumsy if you need to verify whether a key is in a dictionary or not in everywhere in your code. We convert the above code by using get function in dictionary.

student_arr = ["James", "Bicky", "Abhinay", "Peter", "Bicky", "Amy"]

stu_2_count_dict = {}
for student in student_arr:
    stu_2_count_dict[ student ] = stu_2_count_dict.get( student, 0 ) + 1

print(f'{ stu_2_count_dict= }')
# stu_2_count_dict= {'James': 1, 'Bicky': 2, 'Abhinay': 1, 'Peter': 1, 'Amy': 1}

It looks much nicer now. ๐Ÿ˜Ž

4. Counter, element_2_count dictionary

There is a neater and tidier way to handle counting element in list by using built-in class Counter.

from collections import Counter

student_arr = ["James", "Bicky", "Abhinay", "Peter", "Bicky", "Amy"]

stu_counter = Counter(student_arr)
print(f'{ stu_counter= }')
print(f'{ stu_counter["Bicky"]= }')
# stu_counter= Counter({'Bicky': 2, 'James': 1, 'Abhinay': 1, 'Peter': 1, 'Amy': 1})
# stu_counter["Bicky"]= 2

If you would like to know more about Counter, please take a look here

Did you find this article valuable?

Support Ivan Yu by becoming a sponsor. Any amount is appreciated!

ย