Junior — Middle
Can you explain the difference between a data structure set and a dictionary in the context of programming?
sobes.tech AI
Answer from AI
A Set and a dictionary are different data structures with different purposes:
-
Set — a collection of unique elements without order. Used when you need to store a set of unique values and quickly check for membership.
-
Dictionary — a collection of key-value pairs, where each key corresponds to a specific value. Allows quick retrieval of a value by its key.
Example in Python:
# Set
fruits = {'apple', 'banana', 'cherry'}
print('banana' in fruits) # True
# Dictionary
prices = {'apple': 100, 'banana': 50, 'cherry': 75}
print(prices['banana']) # 50
Summary:
- Set stores only unique elements.
- Dictionary stores key-value pairs for quick access by key.