Let me take this a step further. If you’re dealing with large datasets or need advanced operations, the pandas library is your best friend. It’s fast, efficient, and handles CSV-like data effortlessly.
Here’s how you can do it:
import pandas as pd
# Read the CSV data into a pandas DataFrame
df = pd.read_csv('abc.txt', encoding='utf-8-sig')
# Convert the DataFrame to a list of dictionaries
my_list = df.to_dict(orient='records')
# Filter rows where Sect is '2-2'
filtered_list = [d for d in my_list if d['Sect'] == '2-2']
print(filtered_list)
How it works:
pandas.read_csv() reads the file into a DataFrame, which is a highly optimized structure for handling tabular data. Converting it to a list of dictionaries using to_dict() gives you the same flexibility as earlier approaches, but with the added power of pandas for more complex operations. It’s my go-to for parsing and filtering!