python - Comparing the List with Dictionary? -


data1=[{'aa': none, 'bb': 'dffg', 'cc': '0', 'dd': '1234', 'ee': none},  {'aa': 'cdfg', 'bb': none, 'cc': '0', 'dd': 'sc12', 'ee': 'edft'}, {'aa': 'bvkjdi', 'bb': 'hdjd', 'cc': '0', 'dd': none, 'ee': none}, {'aa': none, 'bb': none, 'cc': '0', 'dd': '123dg', 'ee': 'hddk'}]   data2={'aa': ('','cdfg', 'bvkjdi', ''), 'bb': ('dffg','', 'hdjd', ''), 'cc': ('0', '0', '0','0'), 'dd': ('1234', 'sc12', '','123dg'), 'ee': ('', 'edft', '','hddk') } 

data1 list in many dictionaries key values , data2 dictionaries key values.need compare these 2 format different.need figure out , easy way compare 'aa' of data1 'aa' data2 , 'bb' values of data1 'bb' values of data2 remaining things.please me compare this.

you can restructure data1 data2 using dictionary comprehension:

>>> n = {k: tuple(d[k] d in data1) k in data2} >>> n {'aa': (none, 'cdfg', 'bvkjdi', none), 'cc': ('0', '0', '0', '0'),  'dd': ('1234', 'sc12', none, '123dg'), 'ee': (none, 'edft', none, 'hddk'),  'bb': ('dffg', none, 'hdjd', none)} 

since want none match '', can convert too:

>>> n = {k: tuple(d[k] if d[k] not none else '' d in data1) k in data2} >>> n {'aa': ('', 'cdfg', 'bvkjdi', ''), 'cc': ('0', '0', '0', '0'),  'dd': ('1234', 'sc12', '', '123dg'), 'ee': ('', 'edft', '', 'hddk'),  'bb': ('dffg', '', 'hdjd', '')} 

after which:

>>> n == data2 true 

if want compare aa , bb key/value pairs, pull them out:

>>> keys_to_compare = {'aa', 'bb'} >>> d1 = {k: tuple(d[k] if d[k] not none else '' d in data1) k in keys_to_compare} >>> d2 = {k: v k,v in data2.iteritems() if k in keys_to_compare} >>> d1 == d2 true 

or compare them in-place:

>>> all(tuple(d[k] if d[k] not none else '' d in data1) == data2[k] k in keys_to_compare) true 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -