You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
import csv
|
|
|
|
def parse_csv_to_dict(csv_file_path):
|
|
"""
|
|
Parses a CSV file into a dictionary.
|
|
|
|
Parameters:
|
|
- csv_file_path (str): The path to the CSV file.
|
|
|
|
Returns:
|
|
- dict: A dictionary representation of the CSV file.
|
|
"""
|
|
parsed_dict = {}
|
|
|
|
with open(csv_file_path, mode='r', newline='', encoding='utf-8') as csvfile:
|
|
reader = csv.reader(csvfile)
|
|
for row in reader:
|
|
if len(row) < 2:
|
|
continue # Skip rows that do not have at least two columns
|
|
name = row[0].strip()
|
|
if name not in parsed_dict:
|
|
parsed_dict[name] = {}
|
|
|
|
index = 1
|
|
while index < len(row):
|
|
field_type = row[index].strip() if len(row) > index else None
|
|
#print(field_type, end=" ")
|
|
if not field_type:
|
|
break # End of relevant columns for this row
|
|
|
|
if field_type in ('KEY:', 'PARAM:') and len(row) > index + 2:
|
|
key_or_param_name = row[index + 1].strip()
|
|
key_or_param_value = row[index + 2].strip()
|
|
|
|
if field_type == 'KEY:':
|
|
if 'KEY' not in parsed_dict[name]:
|
|
parsed_dict[name]['KEY'] = {}
|
|
parsed_dict[name]['KEY'][key_or_param_name] = key_or_param_value
|
|
elif field_type == 'PARAM:':
|
|
if 'PARAM' not in parsed_dict[name]:
|
|
parsed_dict[name]['PARAM'] = {}
|
|
parsed_dict[name]['PARAM'][key_or_param_name] = key_or_param_value
|
|
|
|
index += 3
|
|
#print("")
|
|
# If no valid field_type was found, set the entry to None
|
|
if name not in parsed_dict:
|
|
parsed_dict[name] = None
|
|
|
|
return parsed_dict
|
|
|
|
if __name__ == "__main__":
|
|
csv_file_path = 'apidetails.csv'
|
|
result = parse_csv_to_dict(csv_file_path)
|
|
print(result)
|