Junior — Middle
What are the main differences between the data structures 'dictionary' and 'set'?
sobes.tech AI
Answer from AI
A dictionary (dict) and a set are built-in data structures in Python, but they serve different purposes:
-
Dictionary (dict) stores key-value pairs. Each key is unique, and you can quickly access the associated value using the key. It is used for mapping and fast data lookup.
-
Set stores unique elements without order and without associated values. It is used for membership testing, removing duplicates, and set operations (intersection, union).
Example:
# Dictionary
my_dict = {'apple': 3, 'banana': 5}
print(my_dict['apple']) # 3
# Set
my_set = {'apple', 'banana', 'apple'}
print(my_set) # {'apple', 'banana'} — duplicates removed