Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item with value from tuple in python

I have a tuple that I fetched from a query, but I'm not experienced with Python so I don't know the right/best way to do this. Here is what the tuple looks like:enter image description here

Now I need something like result.getItemWithKey('111.111.5.1') that returns a single array object or comma separated string ( as it's more useful) like 'object1, 111.111.5.1'


1 Answers

Your result is a tuple of tuples, so you can access it using indexes like this:

>>> result[0]
('object1', '111.111.5.1')
>>> result[0][0]
'object1'
>>> result[0][1]
'111.111.5.1'

You can read more about tuples (and other data structures) in the Python official docs

So your function could look like this:

def get_item(result, key):
    for obj, num in result:
        if num == key:
            return obj, num
like image 100
matino Avatar answered Sep 15 '25 01:09

matino