Home

Searching_dictionary

This is an example of data structures at work. Searching dictionary depending on method used varies in efficiency.

import time

test_dict = {'a': 'wg', 'b': 'fsdfa', 'c': 2, 'd':'afsfs', 'e': 8}

start = time.time()
for _ in range(10_000_000):
    bool('a' in test_dict.keys())

end = time.time()
print(end-start) 
# --> around 3 sec

# dict.keys() -- gives a list and the script iterates over 
# each element

print(test_dict.keys())
>> dict_keys(['a', 'b', 'c', 'd', 'e'])


start = time.time()
for _ in range(10_000_000):
    bool('a' in test_dict)

end = time.time()
print(end-start) # --> around 2 sec

# dict implement hash function --> no need to iterate over each element

source: https://www.youtube.com/watch?v=b0ladWq-3ws

Tags: Python, Data_structures, Dictionary, Data_structures_in_action