Junior — Middle
Which data structure generally provides better performance: list or dictionary?
sobes.tech AI
Answer from AI
A dictionary (dict) generally provides better performance for key access than a list. This is because a dictionary is implemented based on a hash table, which allows search, insertion, and deletion operations to be performed in amortized O(1) time. In contrast, a list requires iterating over elements to find an item, which takes O(n) time.
Example:
my_list = [1, 2, 3, 4, 5]
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Searching for an element in a list
if 3 in my_list:
print("Found")
# Searching by key in a dictionary
if 'b' in my_dict:
print("Found")
Therefore, if access speed by key is important, a dictionary is preferable.