if key in dict python time complexity

Solutions on MaxInterview for if key in dict python time complexity by the best coders in the world

showing results for - "if key in dict python time complexity"
Anne
07 Jul 2016
1"""
2Time complexity of looking for a value in a hashable object is O(1). Dictionary
3keys are hashable.
4The code below is just for demonstration purposes, feel free to run it and see
5that the plot has no correlation with n.
6"""
7
8from time import time as now
9import matplotlib.pyplot as plt
10from numpy.random import randint
11from tqdm import tqdm
12
13max_n = 100000
14samples_per_n = 10
15dummy_dict = dict()
16n = [i for i in range (max_n)]
17time = []
18
19for i in tqdm(range(max_n), desc='Looking for keys as dictionary grows in size...'):
20    dummy_dict[i] = i
21    times = []
22    for _ in range(samples_per_n):
23        dummy_key = randint(low=0, high=max_n)
24        start = now()
25        if dummy_key in dummy_dict:
26            pass
27        times.append (now() - start)
28    time.append(sum(times) / len(times))
29
30plt.plot(n, time)
31plt.xlabel('N')
32plt.ylabel('Time[s]')
33plt.ylim(-0.02, 0.02)
34plt.show()