Junior — Middle
Millised on peamised erinevused sõnastiku ja massiivi andmestruktuuri vahel?
sobes.tech AI
Vastus AI-lt
The main differences between a dictionary and an array:
-
Storage structure:
- Array: an ordered collection of elements, accessible by index (integer).
- Dictionary: an unordered collection of key-value pairs, accessible 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 useful 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