No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Playgrounds: Lee un CSV para calcular el total de gastos

38/44

Aportes 384

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Aporto mi solución:

def read_csv(path):
   with open(path, 'r') as csvfile:      
      total = sum(int(r[1]) for r in csv.reader(csvfile))
      return total

response = read_csv('./data.csv')
print(response)

Hola, dejo una solución utilizando la función de orden superior reduce:

import csv
import functools

def read_csv(path):
   # Tu código aquí 👇
   with open(path) as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      data = list()
      for line in reader:
         data.append(int(line[1]))
   total = functools.reduce(lambda x,y: x+y, data)
   return total

response = read_csv('./data.csv')
print(response)

Mi solución, creo que queda más eficiente haciendo la lógica de la suma directamente en vez de convertir los datos a lista para después usar la función ya incluida

import csv

def read_csv(path):
   sum = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile)
      for data_set in reader:
         sum += int(data_set[1])
   return sum
   
sum_csv = read_csv('./data.csv')
print(sum_csv)

Espero que les sirva:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter= ",")
      dic = { j: k for j,k in reader}
      total = 0
      for valor in dic.values():
         total += int(valor)
      
      return int(total)
response = read_csv('./data.csv')
print(response)

Aqui es donde se pone bueno todo esto, las diferentes respuestas de todos ustedes me molan

Aquí les comparto mi solución:

import csv

def read_csv(path):
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      total = [int(row[1]) for row in reader]
   return sum(total)

response = read_csv('./data.csv')
print(response)

Aqui mi solucion al reto:

def read_csv(path):
   total = 0
   with open(path, 'r', encoding='utf-8') as f:
      data = csv.reader(f)
      for _, val in data:
         total += int(val)

   return total

my solucion

import csv

def read_csv(path):
   # Tu código aquí 👇
   with open (path,"r") as csvfile:
      reader = csv.reader(csvfile,delimiter=",") 
      total_num=[]        
      for row in reader:     
         total_num.append(int(row[1]))  
        
     
   total= sum(total_num)     
   
   return total

response = read_csv('./data.csv')
print(response)

Este ejercicio me pareció perfecto para aplicar la función reduce aprendida en clases anteriores

import csv
import functools

def read_csv(path):
   with open(path) as csvfile:
      reader = csv.reader(csvfile, delimiter = ',')
      total = functools.reduce(lambda acc, row: acc + int(row[1]), reader, 0)
      return total

response = read_csv('./data.csv')
print(response)
![](https://static.platzi.com/media/user_upload/image-41453a92-f4a0-4f5a-a1ca-06fe168c6ecb.jpg)

Aporto mi solución:

import csv

def read_csv(path):
   # Tu código aquí 👇
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   # Tu código aquí 👇
   with open(path, 'r') as archivoCSV:
      archivo = csv.reader(archivoCSV, delimiter = ',')
      total = sum(int(fila[1]) for fila in archivo)
   return total

response = read_csv('./data.csv')
print(response)

Aquí mi solución. Muy complicada creo en mi opinion jejeje

import csv

def run():
    def read_csv(path):
        with open(path, "r") as file:
            reader = csv.reader(file, delimiter=",")
            dicty = {x:y for x,y in reader}
            return dicty
    dicty = read_csv("./data.csv")
    print(dicty)
    result = int(dicty["Administration"]) + int(dicty["Marketing"]) + int(dicty["Purchasing"]) + int(dicty["Human Resources"]) + int(dicty["Shipping"]) + int(dicty["IT"]) + int(dicty["Public Relations"]) + int(dicty["Sales"]) + int(dicty["Executive"]) + int(dicty["Finance"])
    print(f"El precio total es {result}") 

if __name__ == "__main__":
    run()
![](https://static.platzi.com/media/user_upload/image-8047c163-e39c-48f5-9745-5b4c9e6f57ef.jpg)import csv def read\_csv(path):   # Tu código aquí 👇   with open(path, 'r') as csvfile:    reader = csv.reader(csvfile)    data = dict(reader)    valuesDict = data.values()        total = 0   for number in valuesDict:      intNum = int(number)      total += intNum   return total response = read\_csv('./data.csv')print(response)```js import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) data = dict(reader) valuesDict = data.values() total = 0 for number in valuesDict: intNum = int(number) total += intNum return total response = read_csv('./data.csv') print(response) ```Al ser nueva con esto, me costó un poco (bastante) pero a la final lo logré y pude hacerlo.
Aquí mi solución: ```python import csv, functools def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as file: reader = csv.reader(file, delimiter=',') totals = map(lambda item: int(item[1]), reader) total = functools.reduce(lambda counter, item: counter + item, totals) return total response = read_csv('./data.csv') print(response) ```
import csv

def read_csv(path):
   # Tu código aquí 👇
   with open(path, 'r') as csv_file:
      reader = csv.reader(csv_file)
      # print(reader)
      total = sum(int(r[1]) for r in reader)
   return total

response = read_csv('./data.csv')
print(response)
import csv

def read_csv(path):
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)

Quise ponerle un encabezado a la data del archivo csv y trabajar con ello:

import csv

def read_csv(path):
       with open(path, 'r') as csvfile:
        data = []
        for row in csvfile:
            row = row.rstrip('\n')
            columns = row.split(',')
            area = columns[0]
            expenses = int(columns[1])
            data.append({
                'Area': area,
                'Expenses': expenses
            })
            expenses = sum(list(map(lambda item: item['Expenses'], data)))
        return expenses
           
if __name__ == '__main__':
    data = read_csv('./data2.csv')
    print(data)
import csv

def read_csv(path):
   lista=[]
   with open(path,"r") as file :
      reader = csv.reader(file,delimiter = ",")
      header = ["Area", "Gasto"]
      for linea in reader:
         iterable=zip(header,linea)
         dic = {key:valor for (key,valor) in iterable}
         lista.append(dic)
   gastos = [lis["Gasto"] for lis in lista]
   gastos = list(map(lambda x : int(x),gastos))
   total = sum(gastos)
   return total

response = read_csv('./data.csv')
print(response)
Mi solución: ```python import csv def read_csv(path): with open(path, "r") as data: reader = csv.reader(data, delimiter = ",") total = sum(int(row[1]) for row in reader) return total response = read_csv('./data.csv') print(response) ```
```python import csv from functools import reduce def read_csv(path): total = 0 with open(path,'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') total = reduce(lambda x, y: x + int(y[1]), csv_reader, 0) return total response = read_csv('./data.csv') print(response) ```import csvfrom functools import reduce def read\_csv(path):   total = 0   with open(path,'r') as csv\_file:    csv\_reader = csv.reader(csv\_file, delimiter=',')    total = reduce(lambda x, y: x + int(y\[1]), csv\_reader, 0)   return total response = read\_csv('./data.csv')print(response)
Mi solución, con algunos comentarios del funcionamiento ```python #Importamos el modulo para manejar archivos CSV import csv #Definimos la función read_csv que se encargara de toda la operacion def read_csv(path): # Tu código aquí 👇 #Abrimos el archivo CSV en modo lectura with open(path, 'r') as csvfile: #Definimos la variable de total para guardar ahí la suma de los gastos total =0 #Generamos el iterable reader que contiene la informacion de cada renglon del CSV reader = csv.reader(csvfile, delimiter=',') #Con el iterable reader, y el ciclo for,vamos recorriendo cada renglón y sumando el valor del segundo elemento de cada renglon al resultado "total" for rows in reader: total += int(rows[1]) return total response = read_csv('./data.csv') print(response) ```
mi solución: ```python import csv def read_csv(path): with open(path, 'r') as file: reader = csv.reader(file, delimiter=',') sum_ = [] for row in reader: sum_.append(int(row[1])) return sum(sum_) response = read_csv('./dt.csv') print(response) ```import csv def read\_csv(path): with open(path, 'r') as file: reader = csv.reader(file, delimiter=',') sum\_ = \[] for row in reader: sum\_.append(int(row\[1])) return sum(sum\_) response = read\_csv('./dt.csv')print(response)
Esta es mi propuesta de respuesta, pero antes, sobre la complejidad de estas funciones: Complejidad Temporal (Velocidad) 1. **Lectura del archivo con** `csv.reader`**:** La lectura del archivo se realiza línea por línea, usando un iterador interno de Python. Su complejidad es **O(n)**, donde `n` es el número de líneas en el archivo CSV. 2. **Append a la lista (**`expenses.append(int(row[1]))`**):** En el peor de los casos, hay `n` operaciones `append` (una por cada línea). La complejidad temporal de cada `append` es **O(1)**. Entonces, en total, esto también toma **O(n)**. 3. **Suma de los valores en la lista (**`for i in expenses:`**):** Una vez que tenemos la lista `expenses` con `n` elementos, sumamos todos los elementos de la lista, lo cual tiene una complejidad de **O(n)**, ya que recorremos todos los elementos una vez. ```js import csv def read_csv(path): # Tu código aquí 👇 expenses = [] total = 0 with open(path, 'r') as csvfile: lines = csv.reader(csvfile, delimiter=',') for row in lines: expenses.append(int(row[1])) for i in expenses: total = total + i return total response = read_csv('./data.csv') print(response) ```
Esta fue la solución a la que llegué, siguiendo el principio "Simple es mejor que complejo" del Zen de Python: ```python import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, 'r+') as csvfile: reader = list(csv.reader(csvfile, delimiter = ',')) for item in reader: total += int(item[1]) return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   total = 0   with open(path, 'r+') as csvfile:      reader = list(csv.reader(csvfile, delimiter = ','))      for item in reader:         total += int(item\[1])   return total response = read\_csv('./data.csv')print(response)
def read\_csv(path):   # Tu código aquí 👇   total = 0   with open('./data.csv', 'r') as csv\_file:    body = csv.reader(csv\_file, delimiter=',')    for item in body:        try:            total += int(item\[1])        except ValueError:            total +=0    return totaldef read\_csv(path):   # Tu código aquí 👇   total = 0   with open('./data.csv', 'r') as csv\_file:    body = csv.reader(csv\_file, delimiter=',')    for item in body:        try:            total += int(item\[1])        except ValueError:            total +=0    return total
Mi solución, se que no es la solución más práctica, pero me sirvió para practicar otros conceptos. ```js import csv import functools def get_total(acc, row): acc['total']+=int(row['anual_total']) return acc def read_csv(path): total = 0 with open(path, mode='r') as csvfile: reader = csv.reader(csvfile, delimiter=',') data=[] keys = ('area_name', 'anual_total') for raw in reader: iterable = zip(keys, raw) dictionary = {key:value for key, value in iterable} data.append(dictionary) total = functools.reduce(get_total, data, {'total':total})['total'] return total response = read_csv('./data.csv') print(response) ```
```js import csv def read_csv(path): # Tu código aquí 👇 total=0 with open(path,'r') as csvfile: reader=csv.reader(csvfile) for i in reader: if int(i[1])>=0: total+=int(i[1]) return total response = read_csv('./data.csv') print(response) ```
![](https://static.platzi.com/media/user_upload/image-25d94530-81e6-40a0-8d72-8dafcaa17538.jpg)
Esta fue mi solución ```js import csv def read_csv(path): total = 0 with open('data.csv','r') as csvfile: reader = csv.reader(csvfile,delimiter=',') for row in reader: total+= int(row[1]) return total response = read_csv('./data.csv') print(response) ```
Por acá mi solución al reto ```python import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: gasto = int(row[1]) total += gasto return total response = read_csv('./data.csv') print(response) ```Quedo atento a comentarios y sugerencias.
otra alternativa: ```python from csv import reader from functools import reduce def read_csv(path): with open(path, 'r') as file: content = reader(file, delimiter=',') return reduce(lambda x, y: x + y, [int(row[1]) for row in content]) response = read_csv('./data.csv') print(response) ```from csv import reader from functools import reduce def read\_csv(path): with open(path, 'r') as file: content = reader(file, delimiter=',') return reduce(lambda x, y: x + y, \[int(row\[1]) for row in content]) response = read\_csv('./data.csv') print(response)
```js import csv def read_csv(path): total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
Este código abrirá el archivo CSV, leerá cada fila, convertirá el segundo valor de cada fila a un entero y sumará todos estos valores, devolviendo el total. Luego, imprimirá el resultado.
```python def read_csv(path): with open(path, mode="r") as file_processor: return sum([int(row[1]) for row in csv.reader(file_processor)]) ```Aca adjunto la solucion mas pythonica que se me ocurrió aplicando lo visto en el curso
```js def read_csv(path): with open(path, mode="r") as file_processor: return sum([int(row[1])for row in csv.reader(file_processor)]) ```def read\_csv(path): with open(path, mode="r") as file\_processor: return sum(\[int(row\[1])for row in csv.reader(file\_processor)]) Comparto mi solucion, lo mas pythonic posible usando lo que hemos aprendido en todo el curso
import csvimport functools def read\_csv(*path*):    with open(*path*, 'r') as csvfile:        reader = csv.reader(csvfile, *delimiter*=',')        total= functools.reduce(lambda *x*, *y*: *x* + int(*y*\[1]), reader, 0)    return total response = read\_csv('./data.csv')print(response)
```js def read_csvg(path): with open(path, "r") as csvfile: reader = csv.reader(csvfile,delimiter=',') total = sum(map(lambda item: int(item[1]), reader)) #-- 🤷🏻‍♀️ return total ```
import csv def read\_csv(path):   total = 0   with open(path) as csv\_file:      csv\_reader = csv.reader(csv\_file, delimiter=',')      for row in csv\_reader:         total += int(row\[1])   return total response = read\_csv('./data.csv')print(response) ```js import csv def read_csv(path): total = 0 with open(path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
import csv def read\_csv(path):   total = 0   with open(path) as csv\_file:      csv\_reader = csv.reader(csv\_file, delimiter=',')      for row in csv\_reader:         total += int(row\[1])   return total response = read\_csv('./data.csv')print(response)
A mí me imprimía raro el encabezado de Density: "Density (per km²)" Si les muestra caracteres raros a la hora de imprimir, agreguen el argumento `encoding='UTF-8'` a la función `open()` ```js with open(path, 'r', encoding='UTF-8') as csvfile: reader = csv.reader(csvfile, delimiter=',') ```
Si les muestra carácteres raros a la hora de imprimir, agreguen el argumento `encoding='UTF-8'` a la función `open()`. ```js with open(path, 'r', encoding='UTF-8') as csvfile: reader = csv.reader(csvfile, delimiter=',') ````with open(path, 'r', encoding='UTF-8') as csvfile:` ` reader = csv.reader(csvfile, delimiter=',')` A mí me imprimía raro el encabezado de Density: "Density (per km²)"
Si les muestra carácteres raros a la hora de imprimir, agreguen el argumento `encoding='UTF-8'` a la función `open()` ```js with open(path, 'r', encoding='UTF-8') as csvfile: reader = csv.reader(csvfile, delimiter=',') ```A mí me imprimía raro el encabezado de Density: "Density (per km²)"
![](https://static.platzi.com/media/user_upload/Captura%20desde%202024-06-19%2011-39-18-9db31524-a254-4cb3-934e-d3c99dd83517.jpg)
reduce + lambda + list comprehension: ````python import csv import functools def read_csv(path): # Tu código aquí 👇 with open(path, "r") as csv_file: reader = csv.reader(csv_file) total = functools.reduce(lambda counter, item: counter + item, [int(row[1]) for row in reader]) return total response = read_csv('./data.csv') print(response) ```import csvimport functools def read\_csv(path):   # Tu código aquí 👇   with open(path, "r") as csv\_file:      reader = csv.reader(csv\_file)      total = functools.reduce(lambda counter, item: counter + item, \[int(row\[1]) for row in reader])   return total response = read\_csv('./data.csv')print(response) ````
reduce + lambda + list comprehension: ![](https://static.platzi.com/media/user_upload/image-dc09675a-068a-46a1-aa8f-cfcb87043f5c.jpg)
El output del data.csv del desafío da 1499 (chequeado en excel).  La función read\_csv abre el archivo CSV especificado por path, luego recorre cada línea del CSV. Para cada línea, convierte el segundo elemento (el total de gastos del año) a un entero y lo suma al total. Finalmente, devuelve el total. import csv def read\_csv(path):     total = 0     with open(path, 'r') as file:         reader = csv.reader(file)         # next(reader)  # si el CSV tiene cabecera, para este caso no.          for row in reader:             total += int(row\[1])  # Sumar los gastos     return total \# Uso de la función response = read\_csv('./data.csv') print(response)
Comparto mi solucion: ```js import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path,'r') as csv_f: reader = csv.reader(csv_f) for num in reader: total += int(num[1]) return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   total = 0   with open(path,'r') as csv\_f:      reader = csv.reader(csv\_f)      for num in reader:         total += int(num\[1])      return total response = read\_csv('./data.csv')print(response)
```python import csv def read_csv(path): with open(path,'r') as csvgastos: reader=csv.reader(csvgastos, delimiter=',') total={key:int(value) for key,value in reader} tot=sum(total.values()) return tot response=read_csv('./data.csv') print(response) ```
Lo hice con validación de datos. ```js import csv def read_csv(path): sum = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) for total in reader: try: sum += int(total[1]) except ValueError: continue return sum response = read_csv('./data.csv') print(response) ```
Lo hice con una validación de datos.import csv def read\_csv(path):   sum = 0   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile)      for total in reader:         try:            sum += int(total\[1])         except ValueError:            continue     return sum response = read\_csv('./data.csv')print(response) ```js import csv def read_csv(path): sum = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) for total in reader: try: sum += int(total[1]) except ValueError: continue return sum response = read_csv('./data.csv') print(response) ```
Lo hice con una validación de datos.import csv def read\_csv(path):   sum = 0   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile)      for total in reader:         try:            sum += int(total\[1])         except ValueError:            continue  # Ignorar filas con datos no válidos en la segunda columna   return sum response = read\_csv('./data.csv')print(response) ```js import csv def read_csv(path): sum = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) for total in reader: try: sum += int(total[1]) except ValueError: continue # Ignorar filas con datos no válidos en la segunda columna return sum response = read_csv('./data.csv') print(response) ```
Le puse una técnica de manejo de errores por si la columna contiene valores numéricos antes de convertirlos a enteros para evitar errores de ejecución.import csv def read\_csv(path):   sum = 0   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile)      for total in reader:         try:            sum += int(total\[1])         except ValueError:            continue  # Ignorar filas con datos no válidos en la segunda columna   return sum response = read\_csv('./data.csv')print(response) ```python import csv def read_csv(path): sum = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) for total in reader: try: sum += int(total[1]) except ValueError: continue # Ignorar filas con datos no válidos en la segunda columna return sum response = read_csv('./data.csv') print(response) ```
Este lo hice yo, y le puse una verificación de datos por si una columna no tiene valores numericos para evitar errores ```python import csv def read_csv(path): sum = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile) for total in reader: try: sum += int(total[1]) except ValueError: continue # Ignorar filas con datos no válidos en la segunda columna return sum response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   sum = 0   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile)      for total in reader:         try:            sum += int(total\[1])         except ValueError:            continue  # Ignorar filas con datos no válidos en la segunda columna   return sum response = read\_csv('./data.csv')print(response)
Les muestro mi solución comunidad ```js import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, "r") as fileData: fileReader = csv.reader(fileData, delimiter=",") for row in fileReader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
Esta fue mi solución ```python import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open('./data.csv','r') as csvfile: reader = csv.reader(csvfile,delimiter = ',') data = [] suma = 0 for row in reader: suma = suma + int(row[1]) return suma response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   total = 0   with open('./data.csv','r') as csvfile:      reader = csv.reader(csvfile,delimiter  = ',')      data = \[]      suma = 0      for row in reader:         suma = suma + int(row\[1])      return sumaresponse = read\_csv('./data.csv')print(response)
![](https://static.platzi.com/media/user_upload/imagen-216d6dc5-87e1-4e12-8717-d421b90f5fcd.jpg)
![](https://static.platzi.com/media/user_upload/image-498288f1-1204-4756-ae75-1670e826293e.jpg)
![](https://static.platzi.com/media/user_upload/image-2d01aed7-c0dd-488b-bea7-7fceadfbb3fb.jpg)![](https://static.platzi.com/media/user_upload/image-ee5421d5-8f8c-4970-8531-364683aba1d7.jpg)
![](https://static.platzi.com/media/user_upload/image-99740c09-b392-4b2d-924e-a6f4cfa3a114.jpg)
```pythonimport csv def read\_csv(path):   with open(path,'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      prices = \[int(row\[1]) for row in reader]      return sum(prices) response = read\_csv('./data.csv')print(response)```
```python import csv def read\_csv(path):    with open(path,'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      prices = \[int(row\[1]) for row in reader]      return sum(prices) response = read\_csv('./data.csv') print(response) ```
```python import csv def read\_csv(path):   with open(path,'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      prices = \[int(row\[1]) for row in reader]      return sum(prices) response = read\_csv('./data.csv')print(response) ```
`import csv` `def read_csv(path):   with open(path,'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      prices = [int(row[1]) for row in reader]      return sum(prices)` `response = read_csv('./data.csv')print(response)`
import csv def read\_csv(path):   with open(path,'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      prices = \[int(row\[1]) for row in reader]      return sum(prices) response = read\_csv('./data.csv')print(response)
Me costo muchisimo. Despues de 2 horas buque en google como cambiar el 'Valu'e del diccionario en un 'entero' para sumarlos. Tambien revise las respuestas pero no quede convencido con mi solucion. De todas maneras funciona ```js import csv import functools def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as csvfile: #leer el csv reader = csv.reader(csvfile, delimiter=',') #crear el diccionario #al mismo tiempo convertir el value en entero (int) dict = {x : int(y) for x, y in reader} #sumar el Value del diccionario PorFin = sum(dict.values()) return PorFin total = PorFin return total response = read_csv('./data.csv') print(response) ```import csvimport functoolsdef read\_csv(path):   # Tu código aquí 👇   with open(path, 'r') as csvfile:      #leer el csv      reader = csv.reader(csvfile, delimiter=',')      #crear el diccionario      #al mismo tiempo convertir el value en entero (int)      dict = {x : int(y) for x, y in reader}      #sumar el Value del diccionario      PorFin = sum(dict.values())      return PorFin               total = PorFin   return total response = read\_csv('./data.csv')print(response)
Adjunto mi solución:import csv def read\_csv(path): total = 0 with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=",") for row in reader: total += int(row\[1]) return total response = read\_csv('./data.csv')print(response) ```js import csv def read_csv(path): total = 0 with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=",") for row in reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
Adjunto mi solución: ![]()```python import csv def read_csv(path): total = 0 with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=",") for row in reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
```python import csv def read_csv(path): # Tu código aquí 👇 with open(path) as csvfile: reader = csv.reader(csvfile,delimiter=",") acum = 0 for row in reader : acum=acum +int(row[1]) total = acum return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   with open(path) as csvfile:      reader = csv.reader(csvfile,delimiter=",")      acum = 0      for row in reader :         acum=acum +int(row\[1])   total = acum   return total response = read\_csv('./data.csv')print(response)
Mi codigo: ```python import csv def read_csv(path): total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: total+= int(row[1]) return total response = read_csv('./data.csv') print(response) ```
import csv def read\_csv(path):   # Tu código aquí 👇   values = \[]   with open(path,'r') as csvFile:      reader = csv.reader(csvFile,delimiter=',')      for row in reader:         values.append(int(row\[1]))   total = sum(values)   return total response = read\_csv('./data.csv')print(response)
import csv deg read\_csv(path): with open(path, 'r') as csvfile: reader =csv.reader(csvfile, delimiter = '.') header = reader dict ={key: value for key, value in header} for element in reader: dict = {key: value for key, value in reader} return dict response = read\_csv('./data.csv') output = 0 for element in response.values(): number = int(element) output = output + number print(output)
hice esto en replit por que en playground no funciona ?? import csv def read\_csv(file\_path): with open(file\_path, 'r') as csvfile: file\_text = csv.reader(csvfile, delimiter=',') data = (list(file\_text)) print(data) values = \[y\[1] for y in data] print('values = ',values) totals =sum(int(i) for i in values) return totals if \_\_name\_\_ == '\_\_main\_\_': totals = read\_csv(file\_path='./playgrounddata.csv') print(totals)
```js import csv def read_csv(file_name): total_expenses = 0 with open(file_name, newline='') as csvfile: csv_reader = csv.reader(csvfile) for row in csv_reader: total_expenses += int(row[1]) return total_expenses file_name = "data.csv" total_expenses = read_csv(file_name) print("Total de gastos de la empresa:", total_expenses) ```import csv def read\_csv(file\_name):    total\_expenses = 0        with open(file\_name, newline='') as csvfile:        csv\_reader = csv.reader(csvfile)        for row in csv\_reader:            total\_expenses += int(row\[1])        return total\_expenses file\_name = "data.csv"total\_expenses = read\_csv(file\_name)print("Total de gastos de la empresa:", total\_expenses)
```js import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') data = list(reader) total = 0 for sublista in data: numero = int(sublista[1]) # Convertimos el segundo elemento a entero total = total + numero return total response = read_csv('./data.csv') print(response) ```
```python import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') data = list(reader) total = 0 for sublista in data: numero = int(sublista[1]) # Convertimos el segundo elemento a entero total = total + numero return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')       data = list(reader)    total = 0   for sublista in data:      numero = int(sublista\[1])  # Convertimos el segundo elemento a entero      total = total + numero   return total response = read\_csv('./data.csv')print(response)
import csv def read\_csv(path):   # Tu código aquí 👇   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')       data = list(reader)    total = 0   for sublista in data:      numero = int(sublista\[1])  # Convertimos el segundo elemento a entero      total = total + numero   return total response = read\_csv('./data.csv')print(response)
`Utilizando lo aprendido` ```js import csv from functools import reduce def read_csv(path): # Tu código aquí 👇 with open("./data.csv","r") as csvfile: reader = csv.reader(csvfile) total= reduce(lambda x,y:x+y, list(int(x[-1]) for x in reader)) return total response = read_csv('./data.csv') print(response) ```

solucion:

```js import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path,'r') as csvfile: reader= csv.reader(csvfile,delimiter=',') for row in reader: total += int(row[1]) return total response = read_csv('./data.csv') print(response) ```
```python import csv def read_csv(path): # Tu código aquí 👇 with open(path,'r') as csvfile: reader = csv.reader(csvfile,delimiter = ',') Valores = [] for row in reader : Valores.append(row[1]) total = sum(int(r) for r in Valores) return total response = read_csv('./data.csv') print(response) ```import csv def read\_csv(path):   # Tu código aquí 👇   with open(path,'r') as csvfile:      reader = csv.reader(csvfile,delimiter = ',')      Valores = \[]      for row in reader :         Valores.append(row\[1])   total =  sum(int(r) for r in Valores)   return total response = read\_csv('./data.csv')print(response)
Aquí mi solución: ```js import csv import functools def read_csv(path): # Tu código aquí 👇 lista = [] with open(path, 'r') as csvfile: reader = list(csv.reader(csvfile, delimiter = ',')) total = functools.reduce(lambda counter, item: counter + int(item[1]), reader,0) return total response = read_csv('./data.csv') print(response) ```import csvimport functools def read\_csv(path):   # Tu código aquí 👇   lista = \[]   with open(path, 'r') as csvfile:      reader = list(csv.reader(csvfile, delimiter = ','))      total = functools.reduce(lambda counter, item: counter + int(item\[1]), reader,0)   return total response = read\_csv('./data.csv')print(response)

Mi solución al problema

import csv

def read_csv(path):
   total = 0
   # Tu código aquí 👇
   with open("data.csv", "r") as archivo_csv:
      lector_csv = csv.reader(archivo_csv)
      for row in lector_csv:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)
```js import csv def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') for row in reader: total = total + int(row[1]) return total response = read_csv('./data.csv') print(response) ```
```python import csv import functools def read_csv(path): # Tu código aquí 👇 with open(path,'r') as csvfile: reader= tuple(csv.reader(csvfile, delimiter=',')) total = functools.reduce(lambda counter,amount: int(amount[1])+counter,reader,0) return total response = read_csv('./data.csv') print(response) ```
`# here is my solution` `with open(path, 'r') as csvfile: ` `total = sum(int(row[1]) for row in csv.reader(csvfile) if len(row) >= 2) ` `return total`
```js import csv def read_csv(path): # Tu código aquí 👇 with open(path,'r') as csvfile: reader= tuple(csv.reader(csvfile, delimiter=',')) total = sum(map(lambda amount: int(amount[1]),reader)) return total response = read_csv('./data.csv') print(response) ```
```js import csv def read_csv(path): with open(path, 'r') as file_csv: reader = csv.reader(file_csv, delimiter=',') total = sum([int(value) for key, value in reader]) return total response = read_csv('./data.csv') print(response) ```Comprehension list
\#comprehension list import csv def read\_csv(path):   with open(path, 'r') as file\_csv:      reader = csv.reader(file\_csv, delimiter=',')      total = sum(\[int(value) for key, value in reader])    return total response = read\_csv('./data.csv')print(response)
\#Comprehension list: import csv def read\_csv(path):   with open(path, 'r') as file\_csv:      reader = csv.reader(file\_csv, delimiter=',')      total = sum(\[int(value) for key, value in reader])    return total response = read\_csv('./data.csv')print(response)
Dejo mi solución: import csv def read\_csv(path): with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = 0 for row in reader: cantidad = int(row\[1]) total += cantidad return total response = read\_csv('./data.csv') print(response)
Aporto mi solución con un reduce y un list comprehension: ```js import csv import functools def read_csv(path): # Tu código aquí 👇 with open(path,'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = functools.reduce(lambda acum,valor:acum+valor, (int(row[1]) for row in reader)) return total response = read_csv('./data.csv') print(response) ```
No es la solución más elegante, pero lo logré :D ```js import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = [] for row in reader: total.append(row[1]) total_int=[int(n) for n in total] #print (total) #print (total_int) total = sum(total_int) return total response = read_csv('./data.csv') print(response) ```

La forma más humilde de hacerlo

import csv

def read_csv(path):
   # Tu código aquí 👇
   total = 0
   with open(path, 'r') as csvfile:
      reader = csv.reader(csvfile,delimiter=',')
      for row in reader:
         total += int(row[1])
   return total

response = read_csv('./data.csv')
print(response)
```python import csv, functools def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = functools.reduce(lambda ac, row: ac + int(row[1]), reader, 0) return total response = read_csv('./data.csv') print(response) ```
```python import csv, functools def read_csv(path): # Tu código aquí 👇 total = 0 with open(path, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') total = functools.reduce(lambda ac, row: ac + int(row[1]), reader, 0) return total response = read_csv('./data.csv') print(response) ```import csv, functools def read\_csv(path):   # Tu código aquí 👇   total = 0   with open(path, 'r') as csvfile:      reader = csv.reader(csvfile, delimiter=',')      total = functools.reduce(lambda ac, row: ac + int(row\[1]), reader, 0)      return total response = read\_csv('./data.csv')print(response)
```js import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as file: puntero = csv.reader(file,delimiter=',') dic={key:value for key,value in puntero} cont=0 for key in dic: cont+=int(dic[key]) total = cont return total response = read_csv('./data.csv') print(response) ```Creo que pude usar un reduce en vez del for, pero no pude jejeje
```python import csv def read_csv(path): # Tu código aquí 👇 with open(path, 'r') as datos: reader = csv.reader(datos, delimiter = ',') total = sum(int(row[1]) for row in reader) return total response = read_csv('./data.csv') print(response) ```
undefined