This is my first Stack Overflow post so please be understanding. I am new to Python and am attempting exercise 16-7 from Eric Matthes' Python Crash Course 2nd edition where I get a csv dataset and create a program that makes the relevant data into a dictionary which I can then make a map with to display the data.
My problem is that the data I store in variables to be put into the dictionary doesn't seem to go in, leaving the dictionary empty and thus preventing me from creating the map to display the data. Hopefully you will see what I mean from my code below.
# data into list
filename = 'API_SP.DYN.TFRT.IN_DS2_en_csv_v2_1622869.csv'
with open(filename, encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
next(reader)
next(reader)
for row in reader:
country_name = row['Data Source']
# '.strip() or 0' part used to ensure fertility data can be read into fertility without
# error caused by blank '' strings in the data.
# Has to be 'row[None]' to avoid KeyError
fertility = float(row[None][-4].strip() or 0)
code = get_country_code(country_name)
if code:
print(code + ': ' + str(fertility))
else:
print('ERROR - ' + country_name)
# build dictionary of population data
fertility_2018_data = {}
for row in reader:
country_name = row['Data Source']
fertility = float(row[None][-4].strip() or 0)
code = get_country_code(country_name)
if code:
fertility_2018_data[code] = fertility
When I try 'print(fertility_2018_data)' I just get a blank {} dictionary.
Apologies for the big chunk, but I would like to be comprehensive. This is the code as it stands after having attempted some things to fix it including adding the 'with open(filename, etc) as f:' bit in the hopes that adding that part would make the file close properly.
Frankly speaking, I am quite stumped and nothing else I have found online so far has really helped me solve this. If needed I can try edit the post with a link to the .csv file in question if it helps solve this issue. I recognize that my code is probably messy and inefficient, so any other critiques are also okay.
csv.DictReader returns a generator object that can be iterated through only once. You have already iterated through it in the below lines.
for row in reader:
When you use "for row in reader" the second time, there's nothing to iterate through.
A solution I would use is store everthing from the generator into a local variable. Something like:
local_var = []
for row in reader:
local_var.append(row)
and then use this local_var downstream. Or you could initialize the reader once again connecting it to file and then populate "fertility_2018_data".