Mostly Linux & Python syntax notes and hyperlinks.

Thursday, May 23, 2013

Python: given two lists of strings, create 2-d dictionary to hold int values, initialized to 0

>>> L1=['A','B','C']
>>> L2=['y','z']
>>> dd=dict()
>>> for x in L2:
...         d=dict()
...         for q in L1:
...             d[q]=0
...         dd[x]=d
...        
>>> dd
{'y': {'A': 0, 'C': 0, 'B': 0}, 'z': {'A': 0, 'C': 0, 'B': 0}}

Then to use it to count stuff:

>>> L3=['Ax','Bz','Cy','By','Cz']
>>> for x in L2:
...       for q in L1:
...           for s in L3:
...               if x in s and q in s:
...                   dd[x][q]+=1
...                  
>>> dd
{'y': {'A': 0, 'C': 1, 'B': 1}, 'z': {'A': 0, 'C': 1, 'B': 1}}

No comments:

Post a Comment