Getting the First Matching Item in a Python List
00:11 While this is the most efficient method that you can use for this purpose, sometimes you may need to match based on a calculated property of the items, such as their lengths. For example, you might be working with a list of dictionaries, typical of what you might get when processing JSON data.
On-screen, you’ll see some country data from the
country-json repository being saved as a dictionary in a Python file. This will allow the data to be imported quickly across multiple REPL sessions, saving you time if you tackle this course across multiple sittings.
There’s no way to use
in if you need to find a dictionary based on an attribute of it, such as population. The most readable way to find and manipulate the first element in the list based on a calculated value is to use the humble
Instead of printing the target object, you can do anything you like with it in the
for loop body. After you are done, be sure to break the
for loop so that you don’t needlessly search the rest of the list.
03:16 Note that on Python 3.10 and later, you can use structural pattern matching to match these kinds of data structures in a way that you may prefer. On-screen, you’ll see how you can use this technique to match a country with a population of more than a hundred million.
Become a Member to join the conversation.