1

I have two lists with nested dictionaries:

list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]

list 2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]

How would I check if a key within list 1 exists within list 2?

With regards to this example, the keys 'lm_sbu' and 'Name' both exist in list 1 and in list 2. However, the key 'lm_app' and 'lm_app_env' exist in list 1 but not in list 2.

Once I find out the differences, I want to append the differences in a separate list.

Thanks

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
mccoym
  • 21
  • 1
  • 2

3 Answers3

1

You are actually checking for the difference between values (not keys) in which case you could take the set difference of the dictionary values in list1 against those in list2:

s = {v for d in list1 for v in d.values()}.difference(*[d.values() for d in list2])
print s
# set([u'new Name', u'lm_app', u'lm_app_env'])
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Something like this, with the items you are searching for in itemlist. There are shorter ways to do this using libraries, but I like vanilla python.

a = [i for j in [l.items() for l in list2] for i in j]
print "\n".join(filter(lambda item: item in a, itemlist))
Sam Craig
  • 875
  • 5
  • 16
0

Python sets helps with this:

list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]
list2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]

list1_keys = {dictionary['Key'] for dictionary in list1}
list2_keys = {dictionary['Key'] for dictionary in list2}

print 'Keys in list 1, but not list 2: {}'.format(list(list1_keys - list2_keys))
print 'Keys in list 2, but not list 1: {}'.format(list(list2_keys - list1_keys))

Output:

Keys in list 1, but not list 2: [u'lm_app', u'lm_app_env']
Keys in list 2, but not list 1: []