comparing dictionaries to find the identical keys

km srikrishnamohan at gmail.com
Fri Dec 28 08:08:20 EST 2007


Hi

On Dec 28, 2007 4:55 PM, Beema shafreen <beema.shafreen at gmail.com> wrote:

> hi everybody ,
> i need to compare two dictionary's key. I have written a script
> gene_symbol = {}
> probe_id = {}
> result = {}
> def getGene(fname):
>         fh = open(fname , 'r')
>         for line in fh:
>                 yield line
>         fh.close()
> for line in getGene("symbol_hu133"):
>         data1= line.strip().split('#')
>         probe_give = data1[0].strip()
>         gene_give = data1[1].strip()
>         gene_symbol[probe_give] = gene_give
>         #print gene_symbol.keys()
> for line in getGene("gds1428.csv"):
>         data = line.strip().split(',')
>         probe_get = data[0].strip()
>         probe_id[probe_get] = data
> if gene_symbol.keys() == probe_id.keys():
>         print gene_symbol.keys(), probe_id.values()
>
>
> can anybody show me  the error I make here ,while comparing the keys of
> two dictionaries so that i print the values of the  dictionaries whoes Keys
> are Identical
>
> Remember that ur looking for commonly occuring keys between the two
dictionaries.
And dictionary.keys() generates a 'list' of keys in that dictionary.
So, u r comparing a list with another  in an if construct and printing the
same which is not what u want to do.
Ideally u should iterate over a list of items and check out if it is present
or not in the other list and then print corresponding values.

Alternately this can also be done with sets module by converting the list
into a set object and do a  simple intersection of the two sets, by which u
get the commonly occuring items.

HTH
KM

> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071228/7a21f7f8/attachment.html>


More information about the Python-list mailing list