1

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.

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

Nearly the same as the others.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.