简体   繁体   中英

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"})

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.

You can write your own function to get the index:

>>> my_dict = {'files': [{'name': 'Markdown', 'extension': '.md'}, {'name': 'Python', 'extension': '.py'}, {'name': 'Sublime Text Setting', 'extension': '.sublime-settings'}]}
>>> def solve(key, val, lis):
        return next((i for i, d in enumerate(lis) if d[key] == val), None)
... 
>>> solve('extension', '.py', my_dict['files'])
1

This may very well not be the best solution, but you could try this:

i=0
for element in files:
    if '.py' in element:
        break
    else:
        i+=1

At the end of this loop, if it finds the extension you want, 'i' will be the index you're looking for. However, if you wanted a list of each element with an extension:

myElements=[]
for element in files:
    if '.py' in element:
        myElements.append(element)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM