So I’m doing this project in Pycharm and I’m running into a problem where I am unable to call the dictionary I created from the csv.DictReader more than once.
I actually did the counts function first, and it worked perfectly, but none of the functions I tried building after it would work at all, so I moved it under the new function I was working on that finds the mean charges for all of the sub categories within each category. When I moved counts under mean_charges, counts stopped working and started return 0’s
Not only that, but within the mean_charges function, only age_charges returns any data, everything after it returns all 0s as if cannot access the dictionary anymore.
When I did the hurricane project, I accessed the hurricane dictionary several times and it was never an issue, so I am guessing that this is either a pycharm thing, or a csv.DictReader thing.
I’ve attatched my code, but it is obviously unfinished.
If I could access counts, I could significantly shorten the mean_charges function.
The csv.DictReader tool is a bit of funny one if your’re unfamiliar with it. It sits on top of your open file and simply converts each line read through it to a dictionary of some sort. So it’s just a convenient way of organising data you get from the input file. As this relies on the open file it will iterate through the file once but that’s all (it reads each line once and then reaches the end of the file).
If you’re looking to reuse the items you’d probably want to add the imported data into another Python structure (perhaps a list or dictionary) so that you have slightly more permanent copy. The DictReader could be reset in this case by moving the underlying file pointer but that’s unnecessarily complicated.
I guess it’s while you were trying to make this work that the indentation went a little askew. An easier route might just be to import the data and then let the file close (end the with code block, indentation dependent).
Thank you. So instead of doing file_dict = csv.DictReader(file), should I then do something like new_dict =
For row in file_dict:
And then I would be able to iterate through the list as many times as I need? Or is that just extra steps for the same result?
Are you saying I should exit out of the import after saving dictreader to a variable and then I’d be able to use it outside of the import block?
Or am I way off base and I should use different/more csv modules?
And yes, I adjusted the indentions and orders of things in an attempt to resolve the issue, thinking scope may have been the problem. So it’s a little off right now,
Yeah storing it makes sense to me. It’s up to you what you store though, it could be each line of text or it could be a dictionary of the data from your reader tool. You could store the output from DictReader instead if you like, it’s really up to you; whatever seems more appropriate for the next task.