a) Dictionary Methods in Python
A dictionary is a collection of key-value pairs. Here are some common methods:
1. get()
Returns the value for a specified key. If the key is not found, it returns None
(or a default value if specified).
student = {'name': 'Rahul', 'age': 21}
print(student.get('name')) # Output: Rahul
print(student.get('grade', 'Not Assigned')) # Output: Not Assigned
2. items()
Returns a view object containing tuples of key-value pairs.
for key, value in student.items():
print(key, value)
3. keys()
Returns a view object containing the dictionary’s keys.
print(student.keys()) # Output: dict_keys([‘name’, ‘age’])
4. values()
Returns a view object containing the dictionary’s values.
print(student.values()) # Output: dict_values([‘Rahul’, 21])
b) Differences Between a List and a Dictionary
Feature | List | Dictionary |
---|---|---|
Data Format | Ordered collection of values | Unordered collection of key-value pairs |
Access | By index (e.g., list[0] ) | By key (e.g., dict['name'] ) |
Syntax | [] (e.g., [1, 2, 3] ) | {} (e.g., {'a': 1, 'b': 2} ) |
Duplicates | Allows duplicate values | Keys must be unique |
Mutability | Mutable | Mutable |