Unit 04 Notes
Unit 04 Notes
Unit 04 Notes
String Exercise :
o Sample Input: " I am learning python programming and Python is
great! "
o Expected Output:
▪ Words in sentence: ['I', 'Am', 'Learning', 'PYTHON',
'Programming', 'And', 'PYTHON', 'Is', 'Great!']
▪ Word count: 9
▪ Final formatted sentence: "I Am Learning PYTHON
Programming And PYTHON Is Great!"
Dictionary Manipulation
Dictionaries are collections of key-value pairs, and Python offers several
methods to manipulate them.
1. get(): Returns the value for a specified key. If the key doesn't exist, it
returns None (or an optional default value).
person = {'name': 'Deepal', 'age': 22}
print(person.get('name')) # Output: Deepal
print(person.get('address', 'Not Found')) # Output: Not Found
2. keys() / values(): Returns a list of the dictionary’s keys or values.
print(person.keys()) # Output: dict_keys(['name', 'age'])
print(person.values()) # Output: dict_values(['Deepal', 21])
3. items(): Returns a list of key-value pairs.
print(person.items()) # Output: dict_items([('name', 'Deepal'), ('age', 21)])
4. update(): Updates the dictionary with key-value pairs from another
dictionary.
person.update({'address': 'India'})
print(person) # Output: {'name': 'Deepal', 'age': 21, 'address': 'India'}
5. pop(): Removes a key-value pair and returns the value.
age = person.pop('age')
print(age) # Output: 21
print(person) # Output: {'name': 'Deepal', 'address': 'India'}
Difference between pop() & popitem()
6. clear(): Removes all key-value pairs from the dictionary.
person.clear()
print(person) # Output: {}
profession = person.pop('profession')
print("Profession:", profession)
person.clear()
print("Final Dictionary:", person)
Conditional Dictionary
Given a dictionary of items and their prices, {"apple": 10, "banana": 5,
"cherry": 15}, write a program to print only the items whose price is
greater than or equal to 10.
Dictionary Assignment :
1. Create a dictionary with the following key-value pairs:
{'product': 'Laptop', 'brand': 'Dell', 'price': 60000}.
2. Add a new key-value pair to the dictionary: 'warranty': '2 years'.
3. Update the value of the 'price' key to 55000.
4. Print all the keys and values in the dictionary in a user-friendly format.
5. Remove the 'brand' key from the dictionary and print the removed
value.
6. Check if the key 'product' exists in the dictionary. If it exists, print its
value. If not, print "Product not found"
7. Clear all items from the dictionary and show the final state (it should
be empty).