1

I have two tab separated files with multiple columns. I used 2 dictionaries, to store specific column of interest.

import csv
dic1={}
dic2={}
with open("Table1.tsv") as samplefile:
    reader = csv.reader(samplefile, delimiter="\t")
    columns = zip(*reader)
    for column in columns:
        A, B, C, D = columns

with open("Table2.tsv") as samplefile1:
     reader = csv.reader(samplefile1, delimiter="\t")
     columns = zip(*reader)
     for column1 in columns:
        A1, B1, C1 = columns

dic1['PMID'] = A  # the first dictionary storing the data of column "A"
dic2['PMID'] = A1 # the second dictionary storing the data of column "A1"

# statement to compare the data in dic1[PMID] with dic2['PMID'] and print the common

Problem: What is the proper logic /or conditional statement to use to compare the two dictionaries and print the common data in both.

madhead
  • 31,729
  • 16
  • 153
  • 201
MEhsan
  • 2,184
  • 9
  • 27
  • 41

1 Answers1

1

You can use set intersection as:

>>> d1={'a':2,'b':3,'c':4,'d':5}
>>> d2={'a':2,'f':3,'c':4,'b':5,'q':17}
>>> dict(set(d1.items()) & set(d2.items()))
{'a': 2, 'c': 4}

For your specific problem, this is the code:

>>> dic1={}
>>> dic2={}
>>> dic1['PMID']=[1,2,34,2,3,4,5,6,7,3,5,16]
>>> dic2['PMID']=[2,34,1,3,4,15,6,17,31,34,16]
>>> common=list(set(dic1['PMID']) & set(dic2['PMID']))
>>> common
[1, 2, 3, 4, 6, 34, 16]
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
  • Your feedback is valuable ... But I am not sure how to use `dict` and `set` for `dic1['PMID'] = A` and `dic2['PMID'] = A1` to print the common in both. Could you show me how to apply your example in this case? @bhat irshad – MEhsan Nov 26 '14 at 21:06
  • Thank you a lot ... I really appreciate your input :) – MEhsan Nov 26 '14 at 22:24