Iterate over a column containing keys from a dict. Return matched keys from second dict keeping order of keys from first dict
Question: I have been stack with a problem for a couple of days with Python (2.7). I
have 2 data sets, A and B, from 2 different populations, containing ordered
positions along the chromosomes (defined by a name, e.g. rs4957684) and their
corresponding frequencies in the 2 populations. Most of the positions in B
match those in A. I need to get the frequencies in A and B of only those
positions that match between A and B, and in the corresponding order along the
chromosomes.

I created a csv file (df.csv) with 4 columns: keys from A (c1), values from A
(c2), keys from B (c3), values from B (c4).

First I created 2 dicts, dA and dB, with keys and values (positions and
frequencies respectively) from A and B, and looked for the keys that match
between A and B. From the matched keys I generated 2 new dicts for A and B
(dA2 and dB2). The problem is that, since they are dicts, I cannot get the
order of the matched positions in the chromosomes so I figured out another
strategy:

Iterate along c1 and see whether any key from c3 matches the ordered keys in
c1. If yes, return an ordered list with the values (of A and B) of the matched
keys.

I wrote this code:

    
    
    import csv
    from collections import OrderedDict
    
    with open('df.csv', mode='r') as infile: # input file
    # to open the file in universal-newline mode
    reader = csv.reader(open('df.csv', 'rU'), quotechar='"', delimiter = ',')
    dA= dict((rows[1],rows[2]) for rows in reader)
    dB= dict((rows[3],rows[4]) for rows in reader)
    
    import sys  
    sys.stdout = open("df2.csv", "w") 
    
    for key, value in dB:
        if rows[3] in dA.key():
            print rows[2], rows[4]
    

Here the script seems to run but I get no output

    
    
    # I also tried this:
    for row in reader:
        if row[3] in dA.key():
            print row[4]
    

...and I have the same problem.


Answer: As I see, you imported `OrderedDict`, but didn't use it. You should build
`OrderedDict` to save keys order:

    
    
    dict_a = OrderedDict((rows[1],rows[2]) for rows in reader)
    dict_b = dict((rows[3],rows[4]) for rows in reader)
    
    for key, value in dict_a.iteritems():
        if dict_b[key] == value:
            print value
    

