Ertuğrul Altınboğa
Ertuğrul Altınboğa

Reputation: 2607

How can I compare two lists with specific key in dict in python

I want to take two lists with dict value and find the specific values that appear only in first list.

In this case, only compare 'name' key.

a = [
       {'name': 'joseph', 'age': 33}, 
       {'name': 'Emma', 'age': 11}, 
       {'name': 'apple', 'age': 44}
    ]
b = [ 
       {'name': 'apple', 'age': 44}, 
       {'name': 'Emma', 'age': 22}
    ]

returnOnlyOne(a, b) would return [{'name': 'joseph', 'age': 33}], for instance.

The set() solution is not for this case.

Upvotes: 1

Views: 63

Answers (3)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

For efficiency, we first make a set of the names in b, then filter the list a:

from operator import itemgetter

def returnOnlyOne(a, b):
    b_names = set(map(itemgetter('name'), b))
    only_in_a = list(filter(lambda item: item['name'] not in b_names, a))
    return only_in_a

Sample output:

a = [
       {'name': 'joseph', 'age': 33}, 
       {'name': 'Emma', 'age': 11}, 
       {'name': 'apple', 'age': 44}
    ]
b = [ 
       {'name': 'apple', 'age': 44}, 
       {'name': 'Emma', 'age': 22}
    ]

print(returnOnlyOne(a, b))
# [{'name': 'joseph', 'age': 33}]

If you don't like itemgetter, filter and the like, you can write the same using comprehensions:

def returnOnlyOne(a, b):
    b_names = set(item['name'] for item in b)
    return [ item for item in a if item['name'] not in b_names]

Upvotes: 1

Xenobiologist
Xenobiologist

Reputation: 2151

Nearly the same as the others.

print([ item for item in a if item['name'] not in set(item['name'] for item in b)])

Upvotes: 0

Chris
Chris

Reputation: 29742

Use list comprehension with map. (BTW, what's inside your list is called dict):

[d for d in a if d.get('name') not in list(map(lambda x:x.get('name'), b))]
# [{'age': 33, 'name': 'joseph'}]

Explanation:

  • list(map(lambda x:x.get('name'), b)): gets all name from b
  • d.get('name') not in: checks if name from a doesn't exist in b. (i.e. appear only in first list)

Upvotes: 0

Related Questions