Junior — Middle
How to distinguish a dictionary from a list in implementation and usage?
sobes.tech AI
Answer from AI
A dictionary (dict) and a list (list) in Python differ in structure and usage:
-
Dictionary (dict): stores key-value pairs. Keys are unique and used for quick access to values. The order of elements in modern Python versions is preserved, but its main purpose is an associative array.
-
List (list): an ordered collection of elements, accessed by index. Allows duplicates and changing order.
Example:
# Dictionary
person = {'name': 'Ivan', 'age': 30}
print(person['name']) # access by key
# List
numbers = [10, 20, 30]
print(numbers[1]) # access by index
Use a dictionary when you need to store data with unique keys and quickly retrieve values by them. A list is suitable for ordered collections where order matters and duplicates are allowed.