[Python] How do I access specifically keys and values from CSV files?

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

  1. Stack

    Stack Membro Participativo

    I have a CSV file keeping track of people's score in a game. I read it with csv.DictReader(). How do I create a dictionary with the keys being the names, and the value being the scores?

    CSV file example:

    name,Game_1, Game_2, Game_3
    James,3,7,4
    Charles,2,3,8
    Bob,6,2,4


    Note: the game names can change, and amount of games too..

    Code Example:

    # Dictionary to load scores into
    score_sheet = {}

    # Read CSV file into memory
    with open("scores.txt") as scores_file:
    reader = csv.DictReader(scores_file)

    list_of_games = reader.fieldnames[1:]

    # Load each row seperately
    for row in reader:
    for game in list_of_games:
    score_sheet[row[0]] = {row[game]:row[game[1]}



    # Experiment 1
    # Load each row separately
    for row in reader:
    score_sheet[row[0]] = row[1]


    # Experiment 2
    for row, value in reader:
    print(row, value)


    Desired output:

    score_sheet = {
    'James':{'Game_1':'3'}, {'Game_2':'7'}, {'Game_3':'4'}
    'Charles':{'Game_1':'2'}, {'Game_2':'3'}, {'Game_3':'8'}
    'Bob':{'Game_1':'6'}, {'Game_2':'2'}, {'Game_3':'4'}
    # Optionally:
    # name:[{game:score}, {game:score}, {game:score}]
    }


    Errors:

    score_sheet[row[0]] = {row[game]:row[game[1]}
    # ^^^^^^ KeyError: 0

    score_sheet[row[0]] = row[1]
    # ^^^^^^ KeyError: 1


    for row, value in reader:
    print(row, value)
    #
    # for row, value in reader:
    # ^^^^^^^^^^
    # ValueError: too many values to unpack (expected 2)


    How do I access specific keys or values for dictionaries from a CSV file? Please help me understand what I am missing or misunderstanding. Thank you!

    Continue reading...

Compartilhe esta Página