I have a text file (tackles.txt) that contains basic stats on high school football players - so far it is just last name and number of tackles. For example:
Jones 2.3
Smith 4.6
Dillon 7.8

How can I read that file and come up with the average number of tackles for all players? Should I try to create a list? A dictionary? I am new to python.

I would like to eventually add more data to the file - such as name tackles position year etc.

thanks in advance.

Dani AI

Generated

Good starter thread — the suggestions from (use a numeric key to avoid name collisions) and (list-of-records to hold multiple fields) point in the right direction. Two practical gaps remain: robust parsing of the text file (blank lines, comments, multi-word names) and a simple, extensible storage shape to support future fields (position, year, multiple game entries). The minimal goal — average tackles — can be implemented with a single pass that accumulates sum and count; the same parsing approach scales to build a list-of-dicts for later use.

A minimal, robust reader for the current whitespace file that treats the last token as the numeric tackle value (so names like "Van Dyke 3.2" work) — then computes the average:

total = 0.0
count = 0
with open('tackles.txt', 'r', encoding='utf-8') as fh:
    for line in fh:
        line = line.partition('#')[0].strip()   # drop trailing comments
        if not line:
            continue
        parts = line.split()
        if len(parts) < 2:
            continue
        *name_parts, tackles_tok = parts
        name = " ".join(name_parts)
        try:
            tackles = float(tackles_tok)
        except ValueError:
            continue
        total += tackles
        count += 1

if count:
    avg = total / count
    print(f'Average tackles: {avg:.2f}')
else:
    print('No valid records found.')

When adding more fields, switch to a CSV with a header and use csv.DictReader (less fragile than split()), or store rows in SQLite / a pandas DataFrame if the dataset grows. For keys, prefer a guaranteed-unique id (jersey number or auto id); otherwise keep a list-of-dicts (as suggested) and allow multiple records per surname. Store each game as its own row if seasonal aggregation or per-game stats will be needed later.

Recommended Answers

All 4 Replies

This thread was originally posted as a code snippet by mistake.
Code snippets are for completed working code only.

you can use a dictionary but it won't be wise to use the surname as the key instead use the position number. for the itemvalues you can use a list and you can append new values later if needed so basically you have a list in the dictionary.

you can use a dictionary but it won't be wise to use the surname as the key instead use the position number. for the itemvalues you can use a list and you can append new values later if needed so basically you have a list in the dictionary.

It is not wise IF you are not absolutely sure that you won't have two guys with the same name. Otherwhise this is not a problem...
Having said that, you can use the position number as suggested which is about to be the same as using a list.
To be able to store as many datas as you want, concerning players, you can use a list of dictionary like this :

myPlayerList=[{"name":"Jones",
               "tackles":[5, 6],
               "somethingElse":["aValue", "anotherValue"]},
              {"name":"Smith",
               "tackles":[4, 2],
               "somethingElse":["aValue", "anotherValue"]}
             ]
# then you call a value like this
name=myPlayerList[1]["name"]
tackleNb2=myPlayerList[1]["tackles"][1]

Or, if you want to use the names as keys (considering what has been said about that) :

myPlayerDict={"Jones":{"tackles":[5, 6],
                      "somethingElse":["aValue", "anotherValue"]},
              "Smith":{"tackles":[4, 2],
                      "somethingElse":["aValue", "anotherValue"]}
             }
# then you call a value like this
listOfJonesTackles=myPlayerDict["Jones"]["tackles"]
smithTackleNb2=myPlayerDict["Smith"]["tackles"][1]

Thanks to all. This was very helpful and points me in a better direction than I was going. Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.