Bows
Bows

Reputation: 49

How do I add a csv file to a dictionary as a value

I have created a dictionary dataset = dict() and I have created a list columns:

colums = ["date", "day", "month", "year", "cases", "deaths", "countriesAndTerritories","countryTerritoryId", "countryTerritoryCode", "population2019", "continent", "cumulativeper1000002Weeks"]

Now I have put the columns as the key and I want a csv file as the value. This is the code:

dataset = dict()
for h in colums:
    dataset[h] = ""
print(dataset)

and the outcome:

{'date': '', 'day': '', 'month': '', 'year': '', 'cases': '', 'deaths': '', 'countriesAndTerritories': '', 'countryTerritoryId': '', 'countryTerritoryCode': '', 'population2019': '', 'continent': '', 'cumulativeper1000002Weeks': ''}

However I want to put a csv file into the dictionary as the value

for row in reader:
    dataset[h] = row
print(dataset)

which gives

{'date': '', 'day': '', 'month': '', 'year': '', 'cases': '', 'deaths': '', 'countriesAndTerritories': '', 'countryTerritoryId': '', 'countryTerritoryCode': '', 'population2019': '', 'continent': '', 'cumulativeper1000002Weeks': ['25/09/2020', '25', '9', '2020', '0', '0', 'Afghanistan', 'AF', 'AFG', '38041757', 'Asia', '1.57195684']}

What I want to happen is {'date': '25/09/2020', 'day': '25', 'month': '9' ...... }

Note: the code is

import csv
def read_dataset() -> List[Dict[str,str]]:
    with open('covid-19.csv', 'r') as file:
        reader = csv.reader(file)
        no_head = next(reader, None)
        colums = ["date", "day", "month", "year", "cases", "deaths", "countriesAndTerritories",
              "countryTerritoryId", "countryTerritoryCode", "population2019", "continent", "cumulativeper1000002Weeks"]
        dataset = dict()
        for h in colums:
            dataset[h] = ""
        for row in reader:
            dataset[h] = row
            return dataset
dataset = read_dataset()
print(dataset)

Upvotes: 1

Views: 227

Answers (3)

Arty
Arty

Reputation: 16737

Three-liner specific for your case (needs python -m pip install requests), produces list of dicts, each dict is a row in the form you wanted:

Try it online!

import io, csv, requests
bytes_data = requests.get('https://opendata.ecdc.europa.eu/covid19/casedistribution/csv').content
print(list(csv.DictReader(io.StringIO(bytes_data.decode('utf-8')), delimiter = ',')))

Upvotes: 1

Stefan
Stefan

Reputation: 1934

From the code you posted it is not clear how your file looks like. Assuming it has a single line, like

'25/09/2020','25','9','2020','0','0','Afghanistan','AF','AFG','38041757','Asia','1.57195684'

You could do something like

colums = ["date", "day", "month", "year", "cases", "deaths", "countriesAndTerritories", "countryTerritoryId", "countryTerritoryCode", "population2019", "continent", "cumulativeper1000002Weeks"]

with open('untitled.txt', 'r') as file:
    fcontent = file.read().split(',')

for idx, c in enumerate(colums):
    dataset[c] = fcontent[idx]

Upvotes: 0

bjmc
bjmc

Reputation: 3282

I would suggest checking out the DictReader available in the Python csv module. I think it may save you a lot of trouble by doing what you need automatically.

I suspect your code could be rewritten as:

import csv
from typing import Dict, List, Iterable


def read_dataset(filename: str, custom_headers: Iterable[str] = None) -> List[Dict[str, str]]:
    with open(filename, 'r') as file:
        reader = csv.DictReader(file, fieldnames=custom_headers)
        return list(reader)

my_headers = [
    'date',
    'day',
    'month',
    'year',
    'cases',
    'deaths',
    'countriesAndTerritories',
    'countryTerritoryId',
    'countryTerritoryCode',
    'population2019',
    'continent',
    'cumulativeper1000002Weeks',
]

dataset = read_dataset('covid-19.csv', my_headers)
print(dataset)

Disclaimer: I have not tried running the above code.

This assumes that the csv file you are reading does not have a header row already or that you want to rename the fields with custom names.

Upvotes: 0

Related Questions