Home > Back-end >  Finding value in a list of a list?
Finding value in a list of a list?

Time:10-29

Recently I've been trying to find if a value exists in a list of a list without having to loop through each entry and checking it exists. For example if I have a list like so:

items = [{'userAssetId': 1408823681, 'assetId': 116040828, 'name': 'ExampleItem'}, {'userAssetId': 2605640821, 'assetId': 250395631, 'name': 'ExampleItem2'}]

If it is possible how would I go about finding the list or index that has the assetId of 116040828, without looping through the main list like so?

for item in items:
    if item["assetId"] == 116040828:
        #Found list that includes 116040828

Wondering if something like items.find(116040828) exists.

CodePudding user response:

Using next:

next((item for item in items if item['id'] == 12345), None)

It returns None if not found

CodePudding user response:

Like this:

   next(filter(lambda x:x['id'] == 12345,items), None)

CodePudding user response:

items = [{"id": 12345, "name": "abc"}, {"id": 54321, "name": "cba"}]

found = 12345 in map(lambda x: x.get("id"), items)

print("found: ", found)

if you want the item

items = [{"id": 12345, "name": "abc"}, {"id": 54321, "name": "cba"}]

find = 12345
item = next((item for item in items if item["id"] == find), None)

print(item)
  • Related