dictionary comparison

James Stroud jstroud at mbi.ucla.edu
Thu May 5 13:37:23 EDT 2005


On Thursday 05 May 2005 10:20 am, so sayeth rickle:
> Bill and Jordan, thank you both kindly.  I'm not too well versed in
> functions in python and that's exactly what I needed.  I could see I
> was doing something wrong in my original attempt, but I didn't know how
> to correct it.
>
> It's working like a charm now, thank you both very much.
> -Rick

I thought I'd throw this in to show some things in python that make such comparisons very easy to write and also to recommend to use the patch as key and version as value in the dict.:

Note that the meat of the code is really about 4 lines because of (module) sets and list comprehension. Everything else is window dressing.

James

===================================

# /usr/bin/env python

from sets import Set

# pretending these stripped from file
recc_ary = ["117000-05", "116272-03", "116276-01", "116278-01", "116378-02", "116455-01", "116602-01", "116606-01"]
serv_ary = ["117000-01", "116272-02", "116272-01", "116602-02"]


# use patch as value and version as key
recc_dct = dict([x.split("-") for x in recc_ary])
serv_dct = dict([x.split("-") for x in serv_ary])

# use Set to see if patches overlap
overlap = Set(recc_dct.keys()).intersection(serv_dct.keys())

# find differences (change comparison operator to <,>,<=,>=, etc.)
diffs = [patch for patch in overlap if recc_dct[patch] != serv_dct[patch]]

# print a pretty report
for patch in diffs:
  print "reccomended patch for %s (%s) is not server patch (%s)" % \
             (patch, recc_dct[patch], serv_dct[patch])


-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list