[Python] Use dictionary comprehension to read a CSV file? Python

Discussão em 'Python' iniciado por Stack, Agosto 27, 2025.

  1. Stack

    Stack Membro Participativo

    So I am trying to mimic this code:

    reader = csv.reader(open('filename.csv', 'r'))
    d = {}
    for row in reader:
    k, v = row
    d[k] = v
    print(d)


    Using dictionary comprehension instead of a for loop. All it does it take the key value pairs in the CSV file and put them into a dictionary. Its a simple CSV file with 10 pairs of numbers. It should output like this to match the original:

    {'1': '3.5', '2': '5.6', '3': '1.7', '4': '-0.1', '5': '27', '6': '33', '7': '13.7', '8': '-4', '9': '10.5', '10': '24.8'}


    I am still newish to Python so any help is appreciated! Thank you.

    Continue reading...

Compartilhe esta Página