I got completely lost in figuring out this problem below. Here is the question:
country_population_data.csv how the csv looks like
extract only the country name and its population from the csv. file (eg, 'China', 14442161070)
create an empty dictionary named pop_dict. Then read the country_population_data.csv file, as a list of lines.
for each line of the records, extract a tuple of country name and population, then store it into the empty dictionary.
*requirement: create own function and use it
The answer should look like: {'China': 14442161070, 'India': 13934090380, ...
My first approach was making a function to extract the required items from the csv file as a tuple, but somehow it did not work out and gave me this error. AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
#funtion to split items
with open(csv, 'r') as f:
def str_to_tuple(f)
str_splitted = tuple(f.split(","))
result_tuple = str_splitted.str()[1] + str_splitted.int()[-1]
return(result_tuple)
print(str_to_tuple(f))
And I also was not sure how to put extracted values in a new dictionary. Could anyone help me with this question? It has been just a couple of weeks for me to learn python so bear with my poor codes and explanation.
Any feedback & comments & tips are welcome to get used to this python world!
As this is a question that is part of a course, I will refrain from simply giving you the answer. Instead, I will try to give you some hints, which might help you find the answer by yourself.
My suggestion is that you start with trying to answer the following questions:
How should you call a function in Python? Is that how you do it in your script? Hint: probably not;) If not, how would you fix this?
What is the type of f
(ie print(type(f))
to find out)? Did you expect that to be the type of f
? Hint: probably not;) What do you expect the type of f
to be? Perhaps we need to call.split(",") on a different variable, one that perhaps doesn't exist yet?
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.