Python Programming Module 3 & 4 -
Detailed Answers
MODULE 3: Strings, Dictionaries, and Word Frequency
1. Explain the key Differences between Lists and Dictionaries. List merits of
dictionary over list.
**Lists vs Dictionaries in Python**:
**Lists**:
- Ordered collections of items.
- Indexed by a range of numbers (starting from 0).
- Can contain elements of different data types.
- Duplicates are allowed.
- Syntax: `my_list = [1, 2, 3]`
**Dictionaries**:
- Unordered collections of key-value pairs.
- Indexed using unique keys.
- Keys must be immutable (strings, numbers, tuples).
- Syntax: `my_dict = {"name": "John", "age": 25}`
**Merits of Dictionary over List**:
- Faster access using keys.
- More meaningful data representation (name-value pairs).
- Useful for data lookup and mapping.
- Avoids confusion due to meaningful identifiers.
2. Explain nested dictionary with a programming example: keys(), values(),
items(), get() and setdefault().
**Nested Dictionary** is a dictionary where values can be another dictionary.
```python
student = {
"John": {"age": 21, "course": "CS"},
"Sneha": {"age": 20, "course": "AI"}
}
```
- `keys()`: Returns all top-level keys.
- `values()`: Returns all values.
- `items()`: Returns all key-value pairs.
- `get(key)`: Safe way to retrieve values; returns `None` if key doesn't exist.
- `setdefault(key, default)`: Returns value if key exists, else inserts and returns default.
Example:
```python
print(student.keys()) # dict_keys(['John', 'Sneha'])
print(student["John"].get("age")) # 21
student.setdefault("Anu", {"age": 19, "course": "DS"})
```
3. Demonstrate the following string methods with suitable implementation
along with examples: islower(), upper(), istitle(), split(), partition(), strip(),
isalpha(), isalnum(), isdecimal()
```python
s = "hello World"
print(s.islower()) # False
print(s.upper()) # "HELLO WORLD"
print(s.istitle()) # True if first char of each word is uppercase
print(s.split()) # ['hello', 'World']
print(s.partition(" "))# ('hello', ' ', 'World')
print(" hello ".strip()) # "hello"
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
print("123".isdecimal()) # True
```
4. Explain Python string handling methods with examples: join(), startswith(),
rjust(),strip(), rstrip(), lstrip(), split(), endswith(), ljust(), center()
```python
s = "hello"
words = ["Python", "is", "fun"]
print(" ".join(words)) # 'Python is fun'
print(s.startswith("he")) # True
print(s.endswith("o")) # True
print(s.rjust(10)) # ' hello'
print(s.ljust(10)) # 'hello '
print(s.center(10)) # ' hello '
print(" hello ".strip()) # 'hello'
print(" hello ".lstrip()) # 'hello '
print(" hello ".rstrip()) # ' hello'
```
5. Read a multi-digit number (as chars) from the console. Develop a program to
print the frequency of each digit with a suitable message.
```python
num = input("Enter a multi-digit number: ")
freq = {}
for digit in num:
if digit in freq:
freq[digit] += 1
else:
freq[digit] = 1
for k, v in freq.items():
print(f"Digit {k} appears {v} times")
```
6. Develop a program to print 10 most frequently appearing words in a text file.
```python
file = open("sample.txt", "r")
data = file.read()
words = data.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_freq[:10]:
print(f"{word}: {count}")
```
7. Generate a Python program that creates a dictionary where each key i is an
integer ranging from 1 to n (inclusive), and its corresponding value is i^3.
```python
n = int(input("Enter n: "))
cubes = {i: i**3 for i in range(1, n+1)}
print(cubes)
```
8. Using string slicing, write a Python program to reverse each word in a given
string.
```python
s = "hello how are you"
reversed_words = " ".join([word[::-1] for word in s.split()])
print(reversed_words) # "olleh woh era uoy"
```
MODULE 4: File Handling, CSV, Excel, JSON
1. Explain the concept of file paths, absolute and relative paths.
- **Absolute Path**: Full path from the root directory. E.g.,
`C:/Users/Admin/Desktop/file.txt`
- **Relative Path**: Path relative to the current working directory. E.g., `./data/file.txt`
2. Describe the use of key functions from Python’s ‘os’ module related to file
and directory operations.
```python
import os
# a. Current working directory
print(os.getcwd())
# b. Create directories
os.makedirs("new/folder/structure") # Nested folders
os.mkdir("new_folder") # Single folder
# c. File size
print(os.path.getsize("file.txt"))
# d. Check path
print(os.path.exists("file.txt"))
print(os.path.isfile("file.txt"))
print(os.path.isdir("folder"))
# e. List contents
print(os.listdir("."))
```
3. Develop a python code to remove the Header from CSV Files and store it in
another file.
```python
import csv
with open('input.csv', 'r') as infile, open('output.csv', 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
next(reader) # skip header
for row in reader:
writer.writerow(row)
```
4. Explain csv module and method defined in csv modules with an example.
- `csv.reader()`: Reads CSV rows
- `csv.writer()`: Writes CSV rows
- `csv.DictReader()`: Reads CSV as dictionaries
- `csv.DictWriter()`: Writes dictionaries to CSV
Example:
```python
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
5. Develop a program to sort the contents of a text file and write the sorted
contents into a separate text file.
```python
with open("input.txt", "r") as infile:
lines = infile.readlines()
lines.sort()
with open("output.txt", "w") as outfile:
outfile.writelines(lines)
```
6. Explain openpyxl Module and methods involved in Reading Excel Documents
with an example.
```python
from openpyxl import load_workbook
wb = load_workbook('data.xlsx')
sheet = wb.active
for row in sheet.iter_rows(values_only=True):
print(row)
```
7. Illustrate with examples opening of a file with open() function, reading the
contents of the file with read() and writing to files with write().
```python
# Reading
with open("file.txt", "r") as f:
data = f.read()
print(data)
# Writing
with open("output.txt", "w") as f:
f.write("Hello, Python!")
```
8. Explain json Module and its methods with an example.
```python
import json
# Serialization
data = {"name": "John", "age": 30}
with open("data.json", "w") as f:
json.dump(data, f)
# Deserialization
with open("data.json", "r") as f:
obj = json.load(f)
print(obj)
```