Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

chaitdwivedi
chaitdwivedi

Posted on • Edited on

     

How to fix dictionary access bugs in Python

In this post I am going to discuss how accessing a value in adict can easily introduce a bug in your code and how to fix it.

Access

One of the most common scenarios with dictionaries is accessing a value.

value=my_dict[key]
Enter fullscreen modeExit fullscreen mode

Problem: Ifkey doesn't exist inmy_dict, the code will raise aKeyError

Solution: To avoid this scenario you have three options:

  1. Check ifkey exists before accessing

    ifkeyinmy_dict:value=my_dict[key]
  2. Wrap the access intry-except block

    try:value=my_dict[key]exceptKeyError:...
  3. Use Python'sget function to avoid checking forkey indict

    value=my_dict.get(key)

Since,get option (3) looks the neatest, I tend to use that the most.

Now, suppose for a function I am writing, I am accessing a value fromdict but I only want to proceed if the given key exists in thedict.

I would write something like this:

value=my_dict.get(key)ifnotvalue:raiseMyError('Found bad key')# continue with code
Enter fullscreen modeExit fullscreen mode

At first glance, the code looks fine, but I have introduced a bug in it.

Let me illustrate with an example:

# Assume my_dict as:my_dict={'key1':'value1','key3':[],}
Enter fullscreen modeExit fullscreen mode
KeyBehaviorExpected?
key1Regular code executionYes
key2raisesMyErrorYes
key3raisesMyErrorNo
  • key2 raises the exception sinceget function will returnNone by default for non-existing keys.

  • key3 exists in thedict however my code will still throw an error becauseif not [] is alsoTrue, leading to unintentional behavior.

Quick Bad Fix

Reading points aboutkey2 andkey3 from above, modifying the validation condition seems like the most obvious fix:

value=my_dict.get(key)ifvalueisNone:raiseMyError('Found bad key')
Enter fullscreen modeExit fullscreen mode

This, however, only fixes one symptom/effect of the bug that is when the value is an empty data type like'' or[]. If the value inmy_dict isNone the above code will still raise the error.

Fix

Before writing a fix for your code, it is usually a good idea to think about the root cause of the bug, rather than the symptoms that are showing up. In our case, it was not theif condition that was causing the bug - it was theget function.

I only want to proceed if the given key exists in thedict

To encode the described behavior the correct code block would look something like this:

ifkeyinmy_dict:value=my_dict[key]# rest of codeelse:raiseMyError('Found bad key')
Enter fullscreen modeExit fullscreen mode

Learning

  • Capturing intent is critical in writing robust code.
  • First step to fixing bugs should be to list assumptions and work from there.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Writing Software for Hardware Engineers!
  • Location
    Austin, Texas
  • Education
    M.S. Computer Engineering
  • Joined

More fromchaitdwivedi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp