What is the good utilisation of csv.DictReader()? [closed]

  Kiến thức lập trình

Data filtering

In most cases, only part of the data is used for analysis. The read_data_to_dicts() function returns a list of dictionaries containing all the data.

Write a filter_data() function:

- which takes as argument a dictionary of weather data of the type returned by ``read_data_to_dicts()`` ;
- and returns a simplified dictionary with only the following fields:
    - sta_numer`` ;
    - date;
    - ``t``.

This is an example exercise to help you understand how to use the CSV module.

import csv

def read_data_to_dicts(csvfile):
    """
    Lit un fichier CSV de données météo structurées et retourne une liste de dictionnaires.

    Args:
        csvfile: un fichier au format csv contenant des données météo structurées

    Returns:
        une liste de dictionnaires contenant les données météo
    """
    with open(csvfile, encoding='utf-8') as csvfile:  #newline=''
        reader = csv.DictReader(csvfile , delimiter=';')
        data = [row for row in reader]
    return data

def main():
    file = 'C:/Users/*****/Downloads/data.csv'
    data = read_data_to_dicts(file)
    print(data)

if __name__ == '__main__':
    main()

New contributor

xxxpyxxx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

import csv
from collections import namedtuple

FILENAME = 'c:/xxxxxxxx/xxxxx.csv'

# Définition du namedtuple pour représenter une station météo
Station = namedtuple('Station', ['ID', 'Latitude', 'Longitude', 'Altitude'])

def build_stations_dict(csvfile):
    """
    retourne un dictionnaire des stations météo du fichier passé en argument

    Args:
        csvfile: un fichier au format csv contenant une liste de stations météo

    Returns:
        dictionnaire de namedtuple des informations relatives aux stations météo
        
 
    """
    stations_dict = {}
    
    with open(csvfile, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile, delimiter=';')
        
    for row in reader:
            # Créer un objet Station à partir des données CSV
        station = Station(row['ID'], float(row['Latitude']), float(row['Longitude']), int(row['Altitude']))
            
            # Ajouter au dictionnaire avec le nom de la station comme clé
            stations_dict[row['Nom']] = station
            
    return stations_dict

def main():
    d = build_stations_dict(FILENAME)
    print(d['NICE'])
    print(d['MONTELIMAR'])


if __name__ == '__main__':
    main()

New contributor

xxxpyxxx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT