Junior — Middle
What is the difference between a dictionary and a set data structure?
sobes.tech AI
Answer from AI
Dictionary (dict) and set (set) are different data structures in Python, although both are based on hash tables and provide fast access.
Main differences:
- Dictionary (
dict) stores pairs of "key: value". Keys are unique, and values can be any objects. - Set (
set) stores only unique elements without values.
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 used when you need to store key-value pairs, and a set is used when the collection of unique elements without additional information is important.