a) Identify and explain the following dictionary methods with examples: get(), items(), keys(), values(). b) Differentiate between a list and a dictionary in Python.

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

FeatureListDictionary
Data FormatOrdered collection of valuesUnordered collection of key-value pairs
AccessBy index (e.g., list[0])By key (e.g., dict['name'])
Syntax[] (e.g., [1, 2, 3]){} (e.g., {'a': 1, 'b': 2})
DuplicatesAllows duplicate valuesKeys must be unique
MutabilityMutableMutable

Leave a Reply

Your email address will not be published. Required fields are marked *