Currently, I have a CSV file set out like this:
Element,Weight
"Hydrogen","1"
"Oxygen","16"
Eventually it’ll have all of the elements and their atomic weights next to them, but putting all of that in is rather pointless unless I get this issue solved first.
The main Python program is as follows:
import csv
reader = csv.reader(open("chem.csv", "rb"))
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
if first == "Hydrogen" or "hydrogen":
for Weight in reader:
print Weight
else:
print "No."
Now, as you might be able to tell from that, my aim here is to have the program display the weight of hydrogen as taken from the CSV file, for now. However, currently it just ends up displaying the following:
Enter first element: hydrogen
Enter second element: oxygen
['Element', 'Weight']
['Hydrogen', '1']
['Oxygen', '16']
So, basically, how can I make it so that it goes to the Hydrogen row and then takes the weight value from the second column? I should be able to go from there to nail the rest of the program, but this part has got me stuck.
As a secondary thing, is it at all possible to have it so that I won’t have to have what is essentially a list of elements in the main Python program as well as in the CSV file? It’d cut down a lot on the clutter, but I just can’t get it figured out.
Instead of iterating over the data it is probably nicer to store it in an easy accessible way, e.g. a dictionary mapping name to weight. Then you can just do a look-up for the entered string and display the result (or not if there is none).
Storing your data apart from you program logic can make sense if you want to be able to easily make changes to the data without touching the program. So having a csv-file that is read in is absolutely okay. (As long as the data has a reasonable size)