Home > Mobile >  Storing CSV file in dictionary list of tuples. Each key is a date, each tuple contains 3 correspondi
Storing CSV file in dictionary list of tuples. Each key is a date, each tuple contains 3 correspondi

Time:11-27

An example to demonstrate my problem, suppose the csv file is formatted like:

2022-11-05,Female,30-39,City of London
2022-11-05,Male,60-69,City of London
2022-11-04,Female,70-79,City of London
2022-11-04,Female,60-69,City of London

Should be read into a dictionary like:

{'2022-11-05': [(Female,30-39, City of London), (Male,60-69,City of London), '2022-11-04': [(Female, 70-79, City of London), (Female, 60-69, City of London)]}

When I attempted to read it like:

vaccine_data_reader = csv.reader(vaccine_date_file)
mydict = {rows[0]: [(rows[1],rows[2],rows[3])] for rows in vaccine_data_reader}

I only got one value per key, not multiple lists of tuples for each unique entry.

CodePudding user response:

A more pythonic way to express the same solution is:

for row in vaccine_data_reader:
    try:
        mydict[row[0]].append(tuple(row[1:]))
    except KeyError:
        mydict[row[0]] = [tuple(row[1:])]

CodePudding user response:

I don't think Dictionary Comprehension would be the way here, as dictionary does not allow duplicate keys, so it will just replace the existing one.

for rows in vaccine_data_reader:
    if rows[0] in mydict.keys(): #Checks if the keys already exists
        mydict[rows[0]].append(tuple(rows[1:])) #Appends the value of duplicate
        continue
    mydict[rows[0]] = [tuple(rows[1:])] #Creates a new keys and adds the value
  • Related