2

I have csv file, with column names of: PH, K, Zn, S, Fe ...so on. For each column there hare 3 different types of output, for example:

PH       S       Zn     Fe         Cu   Mn
Acidic   Low    Low     Medium  High    Medium
Alkaline High   Medium  Medium  High    High
Acidic  Medium  Low     Medium  High    High
Neutral High    Low     Medium  High    High
Acidic   Low    Low     Medium  High    High
Acidic   Low    Low     Medium  High    High
Acidic  Medium  Medium  Medium  High    High

I want to give values of

Acidic = 0, Neutral = 1, Alkaline = 2
Low = 0, Medium = 1, High = 2

How to write a code which is automatic convert Acidic=0 , Neutral=1 , Alkaline=2?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Kiran Prajapati
  • 191
  • 2
  • 18

2 Answers2

3

Ok so something like

dicts = {
   'PH' : {'Acidic': 0, 'Alkaline': 1, 'Neutral': 2},
   'S': {'Low': 0, 'High': 1, 'Medium': 2},
   # etc
} 
with open(your_file) as file:
    table = []
    reader = csv.DictReader(file)
    for row in reader:
        new_row = {key: dicts[key][value] for (key, value) in row.items()}
        table.append(new_row)            
Cedric Druck
  • 1,032
  • 7
  • 20
1

Python provides the Enum class. Why you want to use Enums is covered here. In your case they would look something like:

Code:

from enum import Enum
PH = Enum('PH', 'Acidic Neutral Alkaline')
Concentration = Enum('Concentration', 'Low Medium High')

Demo Code:

print(PH['Acidic'].value)
print(Concentration['Medium'].value)

Produces:

1
2

Demo Code2:

for i in range(1, 4):
    ph = PH(i)
    concentration = Concentration(i)
    print(ph, ph.name, ph.value)
    print(concentration, concentration.name, concentration.value)

Produces:

PH.Acidic Acidic 1
Concentration.Low Low 1
PH.Neutral Neutral 2
Concentration.Medium Medium 2
PH.Alkaline Alkaline 3
Concentration.High High 3
Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135