简体   繁体   中英

can someone explain to me what I did wrong?

I need help unscrambling this code. I am only allowed to use these specific lines of code, but I need to 'unscramble' it to make it work. To me, this code looks good but I don't seem to get it to work so I would like to find out why this is the case.

The assignment that I am trying to solve is as follows:

Read in the file using the csv reader and build a dictionary with the tree species as the key and a count of the number of times the tree appears. Use the "in" operator to see if a tree has been added, and if not set it to 1. Print the dictionary with the counts at the end.

My code is as follows:

from BrowserFile import open as _
import csv
with open("treeinventory.csv", "r", newline='') as f:
    count = {}
    reader = csv.reader(f)
    for yard in reader:
        for tree in yard:
            if tree in count:
                count[tree] = 1
            else: 
                count[tree] = count[tree] + 1
print(count)

I would love if someone can help me and also explain why this code is not able to work as it is, i am trying to learn and this would be very helpful!

thank you!

Generally, we don't solve "homework" problems on SO. You should also try to ask specific questions. Also put better titles on your questions. And, as such, I always like to post This to help new question askers out.

Since I'm here: The answer to your assignment is that line 9 and line 11 are swapped.

This is because the logic seems to set that dict count with the key tree is being set to 1 if the key is in the dict, and add 1 to the value stored at count[tree] if it's not in the dict. This will result in a KeyError exception to be thrown when the value is accessed to do this addition in the statement count[tree] + 1 , because, there is no value there yet.

Of course, without the input file, I can't actually run the code to verify it, so please try this out for yourself and update your question with specific issues if any come up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM