Load CSV to search for match in array/dictionary/list
<p>Very new to Python and I'm now learning by trying to write a program to process data from first few lines from multiple text files. so far so good - getting the data in and reformatting it for output.</p>

<p>Now I'd like to change the format of one output field based on what row it sits in in the csv file. The file is 15 rows with variable number of columns.</p>

<p>The idea is that:</p>

<ol>
<li>I preload the CSV file - I'd like to hardcode it into a list or dictionary - not sure what works better for the next step.</li>
<li>Go thru the 15 rows in the list/dictionary and if a match is found - set the output to column 1 in the same row.</li>
</ol>

<p>Example Data:</p>

<pre class="lang-none prettyprint-override"><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM
CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4
DEN, RHO8[1], RHOZ1, RHOZ2, RHOB_HR, RHOB_ME, LDENX
DENC, CRHO, DRHO1, ZCOR2, HDRH2, ZCORQK
DEPT, DEPTH, DEPT,MD
DPL, PDL, PORZLS1, PORDLSH_Y, DPRL, HDPH_LIM, PZLS
DPS, HDPH_SAN1, DPHI_SAN2, DPUS, DPOR, PZSS1
DTC, DTCO_MFM[1], DT4PT2, DTCO_MUM[1], DTC
DTS, DT1R[1], DTSH, DT22, DTSM[1], DT24S
GR, GCGR, GR_R3, HGR3, GR5, GR6, GR_R1, MGSGR
NPL, NEU, NPOR_LIM, HTNP_LIM, NPOR, HNPO_LIM1
NPS, NPRS, CNC, NPHILS, NPOR_SS, NPRS1, CNCS, PORS
PE, PEFZ_2, HPEF, PEQK, PEF81, PEF83, PEDN, PEF8MBT
RD, AST90, ASF60, RD, RLLD, RTCH, LLDC, M2R9, LLHD
RS, IESN, FOC, ASO10, MSFR, AO20, RS, SFE, LL8, MLL
</code></pre>

<p>For example:</p>

<pre><code>BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM
</code></pre>

<p>returns <code>BIT</code></p>

<p>Questions:</p>

<ul>
<li>Is a list or dictionary a better for search speed?</li>
<li>If I use the csv module to load the data does it matter that number of columns aren't same for every row?</li>
<li>Is there a way to search either list or dictionary without using a loop?</li>
</ul>

<p>My attempt to load into list and search:</p>

<pre><code>import csv
with open('lookup.csv', 'rb') as f:
    reader = csv.reader(f)
    codelist = list(reader)
</code></pre>

<p>Would this work for searching for matching code <code>searchcode</code>?</p>

<pre><code>for subcodes in codelist:
    if searchcode in subcodes:
        print "Found it!", subcodes[0]
        break
</code></pre>

<p>I think that you should try with two-dimensional dictionary</p>

<pre><code>new_dic = {}
new_dic[0] = {BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM}
new_dic[1] = {CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4}
</code></pre>

<p>Then you can search for the element and print it.</p>

python list python-2.7 csv dictionary