Skip to content

Instantly share code, notes, and snippets.

@rs77
Created January 26, 2024 00:25
Show Gist options
  • Save rs77/ba8fb8e7b93efc411f892428107bb976 to your computer and use it in GitHub Desktop.
Save rs77/ba8fb8e7b93efc411f892428107bb976 to your computer and use it in GitHub Desktop.
Here's a template I use to convert a CSV file to a list of dictionaries in Python, read more about it here: https://scripteverything.com/read-a-csv-file-to-list-of-dictionaries-in-python/
# The list for where the dictionaries will be stored
result = list()
with open(file_path) as f:
# Do I need to cleanse the keys?
# Yes: but I will manually write the headers...
my_headers = ('Header 1', 'Header 2')
# Yes: but I just want to clean the current headers...
lines = f.readlines()
# Write the line number where the header can be found...
header_line_idx = 0
# OR, loop through the readlines to find the line that
# matches a condition to find the header row...
header_line_idx = [idx for idx, x in enumerate(lines) if re.match(r'^Header', x)][0]
header_row = lines[header_line_idx]
# Create a list of all the elements in the header...
header_list = header_row.split(",")
# Create a cleansing function and iterate through each element
# to get it to be cleaned to the style you want
my_headers = *(cleanse(x) for x in header_row)
# Capturing the CSV file contents into a list of dictionaries
reader = csv.DictReader(f, fieldnames=my_headers)
# Do I need to cleanse/check dictionary or add more
# keys with values?
# No:
result = [*reader]
# Yes:
# Loop through each item and do your value cleansing...
for row in reader:
# Do all the cleansing or extra keys work in here...
# ...
# With the last entry in this nested for-loop being...
result.append(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment