Home > other >  I want to check if a key exists in a dictionary, what is the better between using a get method on di
I want to check if a key exists in a dictionary, what is the better between using a get method on di

Time:06-17

I have a dictionary in python of, say, names of students and their age.

students = {"Mark": 25, "Sundar": 30, "Satya": 40}

I want to check if a student exists in the dictionary. Notice I don't need the value corresponding to the key, I just need to know if a key exists in the given dictionary.

I have two options, first is to

students.get(key, False)

Second is to do

key in students

Which one is better if there is any difference. Particularly trying to understand how these two work under the hood.

CodePudding user response:

I write benchmark like below for 1_000_000 students but consider multi assumption:

  1. As said in the comments and other answer: It's better to use an expressive and readable solution (Use in in this problem and the benchmark say in is better.)
  2. Suppose all value of your dict have value > 0 for checking condition and return True or False with .get().

Benchmark on colab

import random, string
students = {}

# Creating random `student_name as key` and random `number as value` 
for _ in  range(1_000_000):
    key = ''.join(random.choices(string.ascii_uppercase, k=10))
    students[key] = random.choice(range(1,1000))

def dct_get_app(dct, key):
    return dct.get(key, False) > 0

def dct_in_app(dct, key):
    return key in dct


# select  one key from dictionary that exist
%timeit dct_get_app(students, 'VHKVTRNUHI')
# 10000000 loops, best of 5: 169 ns per loop

%timeit dct_in_app(students, 'VHKVTRNUHI')
# 10000000 loops, best of 5: 128 ns per loop

# select one key from dictionary that not exist
%timeit dct_get_app(students, 'A')
# 10000000 loops, best of 5: 162 ns per loop

%timeit dct_in_app(students, 'A')
# 10000000 loops, best of 5: 121 ns per loop

CodePudding user response:

I don't know about under the hood, but

key in students

is definitely preferable to make the code more readable.

  • Related