0

I have a list of objects, that among other attributes have an attribute named "id"


listA = [{"id":"5","age":"44"},{"id":"8","age":"34"},{"id":"15","age":"84"}]

I have a list of strings such as :


listB = ["9","1","7","5","10","15","20"]

I wish to extract into a third list, all object ids from listA that have an id value in listB

the expected result would be :


listResult = ["5","15"]

How can I do this without using loops?

JK2018
  • 429
  • 1
  • 9
  • 23

4 Answers4

3
listA = [{"id":"5","age":"44"},{"id":"8","age":"34"},{"id":"15","age":"84"}]
listB = ["9","1","7","5","10","15","20"]
listC = [ x['id'] for x in listA if x['id'] in listB ]

print(listC) 
# ['5', '15']
0stone0
  • 34,288
  • 4
  • 39
  • 64
3

Another way is using set and the intersection method:

listA = [{"id":"5","age":"44"},{"id":"8","age":"34"},{"id":"15","age":"84"}]
listB = ["9","1","7","5","10","15","20"]

listC = list(set(listB).intersection(set(d['id'] for d in listA)))
print(listC)

The result is ['15', '5'].

Adrien Riaux
  • 266
  • 9
0

You can use filter and list to achieve it, although it would make more sense to simply use list comprehension like in @0stone0 answer.

list_a = [{"id":"5","age":"44"},{"id":"8","age":"34"},{"id":"15","age":"84"}]
list_b = ["9","1","7","5","10","15","20"]
list_a_ids = map(lambda object: object['id'], list_a)
list_result = list(filter(lambda id: id in list_b, list_a_ids))
Victor Oliveira
  • 352
  • 2
  • 10
0

Combining the filter() and map() function with an unpacking assignment will do it without an explicit loop (although these function do perform loops internally):

*listResult, = filter(listB.__contains__,map(lambda d:d["id"],listA))
Alain T.
  • 40,517
  • 4
  • 31
  • 51