Home > Back-end >  Load a .csv-file in a dictionary and search for a specific entry in column using Python
Load a .csv-file in a dictionary and search for a specific entry in column using Python

Time:10-07

(Python 3) I am currently working on the problem to read the given .csv-file properly and load the data into a dictionary. Since I am new to this I can't figure out the right syntax to save the .csv-data in a dictionary named "loaded_csv_data" (1 Challenge). My overall goal is to search in the column "Current Filename" (2 Challenge) for a specific string and if it exists return "True" (3 Challenge).

Path Current Filename File Type Set Date
C:\Users\Dreampeace 2021-10-06_15-10-24 .png 2021-10-06
C:\Users\Dreampeace 2021-10-03_10-10-19 .mov 2021-10-03
C:\Users\Dreampeace 2021-10-01_09-05-55 .jpg 2021-10-01

Raw data

Path;Current Filename;File Type;Set Date
C:\Users\Dreampeace;2021-10-06_15-10-24;.png;2021-10-06
C:\Users\Dreampeace;2021-10-03_10-10-19;.mov;2021-10-03
C:\Users\Dreampeace;2021-10-01_09-05-55,.jpg;2021-10-01

Code

csv_file_handle_r = open(os.path.join(Directory_History_csv, "history-test.csv"), mode = "r", encoding="utf8")
csv_reader = csv.DictReader(csv_file_handle_r, delimiter = ";")

loaded_csv_data = {}
for row in csv_reader:
    print(row)

The code worked for me but I ended up with three different dictionaries printed on the console.

{'Path': 'C:\Users\Dreampeace', 'Current Filename': '2021-10-06_15-10-24', 'File Type': '.png', 'Set Date': '2021-10-06'}
{'Path': 'C:\Users\Dreampeace', 'Current Filename': '2021-10-03_10-10-19', 'File Type': '.mov', 'Set Date': '2021-10-03'}
{'Path': 'C:\Users\Dreampeace', 'Current Filename': '2021-10-01_09-05-55', 'File Type': '.jpg', 'Set Date': '2021-10-01'}

Every answer, advice, help is appreciated. Thank you!

CodePudding user response:

You haven't included in your question what the desired form/structure for the data here would be, so I'm going to do my best to guess.

Challenge 1

csv.DictReader gives you back a dictionary with the detected headers as the keys and the ;-sv as values.

I used collections.defaultdict to make it easier to put everything in a big dictionary for you to use.

import csv
from collections import defaultdict

loaded = defaultdict(list)

with open("t.csv") as in_file:
    csv_reader = csv.DictReader(in_file, delimiter=";")
    for row in csv_reader:
        for key, value in row.items():
            loaded[key].append(value)

print(loaded)
{
  'Path': [
    'C:\\Users\\Dreampeace', 'C:\\Users\\Dreampeace', 'C:\\Users\\Dreampeace'], 
    'Current Filename': ['2021-10-06_15-10-24', '2021-10-03_10-10-19', '2021-10-01_09-05-55'], 
    'File Type': ['.png', '.mov', '.jpg'], 
    'Set Date': ['2021-10-06', '2021-10-03', '2021-10-01'
  ]
}

Challenges 2 & 3

From here on, you can get the list of filenames by accessing the 'Current Filename' key in the dictionary and do a linear search for the specific string.

  • Related