Junior — Middle
What are the main differences between a dictionary data structure and an array?
sobes.tech AI
Answer from AI
Main differences between a dictionary and an array:
-
Storage structure:
- An array is an ordered collection of elements, accessed by index (an integer).
- A dictionary is an unordered collection of key-value pairs, where access is by key.
-
Type of keys:
- In an array, keys are indices (usually integers).
- In a dictionary, keys can be of different types (strings, numbers, etc.).
-
Access and search:
- Access by index in an array is very fast (O(1)).
- Search by key in a dictionary is also usually very fast (O(1)), but keys are not necessarily ordered.
-
Usage:
- Arrays are suitable for storing ordered data.
- Dictionaries are convenient when you need to store data with unique keys for quick access.
Example in Swift:
let array = ["apple", "banana", "cherry"]
print(array[1]) // banana
let dictionary = ["apple": 3, "banana": 5, "cherry": 2]
print(dictionary["banana"]!) // 5