Middle
What is the difference between a dictionary and a set in Python?
sobes.tech AI
Answer from AI
A dictionary (dict) and a set in Python are both collections based on hash tables, but with different purposes and data structures.
-
Dictionary (dict) stores key-value pairs. Each key is unique, and the value can be any object. It is used for fast data access by key.
-
Set stores unique elements without 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', 'cherry'}
print('banana' in my_set) # True
Thus, a dictionary is a mapping of keys to values, and a set is simply a collection of unique elements.