'How do I make a function that reads a csv, converts its lists into dictionaries to result in a certain output in python?

A csv file in python which includes a list of integers and string such as:

Sunset,61,South,2002-12-28,48,3,25,168,42,13

Sunrise,42,North,2012-02-05,84,3,39,141,13,115

How would I make a function which would, open and read the csv, convert it into a dictionary (in this case would be named dict) so that I could put in an input like this in the function:

sun_state(dict, 61)

and get an output of:

[ '2002-12-28', '84', '4', '49', '308']

the format of the output follows respectively:

The date, three integers after the date and the sum of the last three integers.

If I had made any problems with my question, please do tell, I would love the help of any kind, thank you.



Solution 1:[1]

You could simply read a csv file by using pandas and create a dictionary (although I could not understand your output given your explanation) as follows:

Code:

import pandas as pd
if __name__ == '__main__':
    df = pd.read_csv("data/id_to_date.csv", header=None, names=["Sunset","ID","Direction","Date","col1","col2","col3","col4","col5","col6"])
    sun_dict = {}
    for row_id, row in df.iterrows():
        values = [row["Date"], row["col1"], row["col2"], row["col3"], sum([row["col4"], row["col5"], row["col6"]])] 
        sun_dict[row["ID"]] = values
    print(sun_dict[61])

Result:

['2002-12-28', 48, 3, 25, 223]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abysslover