Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object inside an array list by its property value in Python

I'm trying to write a Sublime Text 2 plugin and get some value inside a .subilme-settings file.

{
"files":
    [
        {
            "name" : "Markdown",
            "extension" : ".md"
        },{
            "name" : "Python",
            "extension" : ".py"
        },{
            "name" : "Sublime Text Setting",
            "extension" : ".sublime-settings"
        }
    ]
}

This is my first time with Python and I don't know how to do it, does exists something like:

my_array.indexOf({"extension":".py"})
like image 224
vitto Avatar asked Sep 06 '25 03:09

vitto


1 Answers

Python lists do have an index method. But it only finds values that are equal to the argument, not values that have an argument that matches your partial value.

There's really nothing in Python that finds partial-structure matches like this; you can search/filter/etc. on equality, or on a predicate function, but anything else you have to write yourself.

The easiest way to do this is with a loop. You can write it explicitly:

for index, element in enumerate(my_array):
    if element["extension"] == ".py":
        return index

… or in a comprehension:

return next(index for index, element in enumerate(array)
            if element["extension"] == ".py")

Alternatively, you can turn the matching into a function, and pass it to filter, or use it as a key function in a more complex higher-order function, but there doesn't seem to be any real advantage to that here.

And of course you can write your own indexOf-like function that matches partial structures if you want.

like image 122
abarnert Avatar answered Sep 07 '25 16:09

abarnert