python - Compare two lists of tuples -


old = [('ver','1121'),('sign','89'),('address','a45'),('type','00')] new = [('ver','1121'),('sign','89'),('type','01')] 

i need compare new list against old 1 based on first element of tuples, , show difference between whatever elements new list has, output should like:

match     : ver   =   1121 match     : sign  =   89 mismatch  : type  =   01 (old : 00) 

i matching tuples below list comprehension not think beyond it.

my_list = [(a,b) (a,b) in new (c,d) in old  if ((a==c) , (b==d))] print( my_list) 

please suggest me way it.

edit

i sorry not being clear on question , did not mention 1 more thing, keys in list can repetitive, meaning list can like:

old = [('ver','1121'),('sign','89'),('address','a45'),('type','00'),('ver','sorry')]  new = [('ver','1121'),('sign','89'),('type','01'),('ver','sorry)] 

update

thanks @holdenweb, i've made changes code , seems providing expected output, please suggest if there flaws.

old = [('ver','1121'),('sign','89'),('address','a45'),('type','00'),('ver','works?')] new = [('ver','1121'),('sign','89'),('type','01'),('ver','this')]  formatter = "{:12}: {:8} = {}".format newfmter = "{} (old : {})".format  kv_old = [] i,(kn, vn) in enumerate(new):     vo = [(j,(ko,vo)) j,(ko, vo) in enumerate(old) if (ko==kn) ]     idx,(key,val) in vo:         if idx >=i:             kv_old = [key,val]             break;      if kv_old[1]==vn:         print(formatter("match", kv_old[0], kv_old[1]))     else:         print(formatter("mismatch", kn, newfmter(vn, kv_old[1]))) 

sometimes list comprehension isn't answer. may 1 of times. also, don't handle case key present in old not in new - include case here, though can chop out code if isn't relevant. handle case of keys missing new, didn't go far.

old = [('ver','1121'),('sign','89'),('address','a45'),('type','00')] new = [('ver','1121'),('sign','89'),('type','01'),("sneaky", 'not there before')] formatter = "{:12}: {:8} = {}".format newfmter = "{} (old : {})".format  (kn, vn) in new:     if any(ko==kn (ko, vo) in old):         ko, vo = [(ko, vo) (ko, vo) in old if ko==kn][0]         if vo==vn:             print(formatter("match", ko, vo))         else:             print(formatter("mismatch", kn, newfmter(vn, vo)))     else:         print(formatter("new", kn, vn)) 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -