Skip to content
Advertisement

How to use a CSV file and use the CSV file to have an input from a user?

I have dataset about car accidents statistics by using a .csv file. I want the user to type in State and all of the information about that State gets displayed for the user to see. How can do that?

Dataset:

JavaScript

I’m thinking of something like this:

JavaScript

Advertisement

Answer

I suggest you use the standard-library’s csv module to read the file. Specifically the csv.DictReader class which will convert each row of the CSV file into a Python dictionary which will make processing it easier.

The following code shows how to do that and also stores all the state dictionaries into a higher level stateDB dictionary so that the name of each state is associated with information about it, effectively making it a “database”. Note that the state names are converted to all uppercase to simplify look-ups.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement