1

For dictionaries:

dict1={pk1:date1, pk2:date2, pk3:date3, pk5:date5}
dict2={pk1:date11, pk3:date13, pk6:date16}

I am trying to compare the values between dict1 and dict2, where for a given pk, if the date in dict1 is less than dict2it will return "Old record". Else if value in dict1 is more recent than dict2(or k:v pair is missing in dict2) , it returns datetime.now() - value from dict1.

So the resulting dictionary may look like this:

dict3={pk1: datetime.now()-date1, pk2: datetime.now()-date2, pk3: "old record", pk5: datetime.now()-date5}  

(assuming date1 is more recent than date 11 and date3 is more recent than date13.)

Comparing two dictionaries in Python seems to be a good starting point, but I don't quite understand what all is going on there to edit it to my situation.

Community
  • 1
  • 1
David__
  • 365
  • 2
  • 6
  • 20

1 Answers1

4

You could dictionary comprehension:

{k1:datetime.now() - v1 if (k1 not in dict2 or v1 > dict2[k1]) 
                      else 'Old record' 
 for k1,v1 in dict1.iteritems()}

It says "if k1 is not in dict2, or it exists and dict1[k1] > dict2[k1] then do datetime.now() - dict1[k1]. Otherwise, "old record"."

mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
  • Thanks, works great. I saw I had an error in my Q, that I have fixed (dict3 contradicted my text). If the value is missing in dict2, then it should return datetime.now()-value, instead of "Old record" as was indicated in the original typing (but was correct in the dict3). Please update your answer and I will mark it as correct. – David__ Mar 14 '12 at 01:40