Python Add Key to Dict conditionally
Question: I'm trying to generate a dict from a list of headers that "associates" columns
of data to the same experiment. For example, I want to turn:

    
    
    headers = ["A_1","A_2","A_3","B_1","B_2","B_3"]
    

into

    
    
    cols = { 1 : {'A' : 0, 'B' : 3}, 2: {'A' : 1, 'B' : 5} ... }
    

My code is as follows:

    
    
    cols = {}
    headers = ["A_1","A_2","A_3","B_1","B_2","B_3"]
    
    col_number = 0
    for header in headers:
       run_number = header[-1:]
       cols[ run_number ] = {}
    
       if "A_" in header:
          cols[ run_number ][ 'A' ] = col_number
       if "B_" in header:
          cols[ run_number ][ 'B' ] = col_number
    
       col_number += 1
    print cols
    

This Outputs only the last "B" columns:

    
    
    {'1': {'B':3}, '2':{'B':5}... }
    

HOWEVER, if I try a simple experiment at the command shell, this notation
seems to work well...

    
    
    cols = {}
    cols[1] = {}
    cols[1]['A'] = 1
    cols[1]['B'] = 2
    print cols
    
    >> {'1' : {'A':1,'B':2} }
    

why?

**EDIT:** Just needed another set of eyes I guess. The issue was this line in
the loop...

    
    
        cols[ run_number ] = {}
    

It overwrites cols[ run_number ] to an empty dict every time a column from a
pre-existing run_number is reached.


Answer: Your loop is overwriting this important variable and setting it to an empty
dict:

    
    
    cols[ run_number ] = {}
    

This means it gets through the "A_" strings for the various numbers and then
when it's onto the "B_" strings, it overwrites all the `run_number` keys it
already created for the "A_" strings.

You should try something like the following instead:

    
    
    if run_number not in cols:
       cols[ run_number ] = {}
    

Alternately, you could try to use
[defaultdict](https://docs.python.org/3.5/library/collections.html)

