Get element with value from tuple in python
I have a tuple that I have selected from a query, but I have no experience with Python, so I don’t know how to do this correctly / best. This is what a tuple looks like:
Now I need something like result.getItemWithKey('111.111.5.1')
that returns an object with one array or comma (which is more useful) like 'object1, 111.111.5.1'
You can find a specific tuple in the result list, iterate over the list and check the value of the second element of each tuple (which is your key):
results = [('object%d' % i, '111.111.5.%d' % i) for i in range(1,8)]
key = '111.111.5.4'
result = None
for t in results:
if t[1] == key:
result = t
print result
Output:
('object4', '111.111.5.4')
This demonstrates accessing an element in a tuple with a zero-based index (1 in this case means the second element). Your code will be more readable if you unpack the tuples in a for loop:
for obj, value in results:
if value == key:
result = (obj, value)
Your results may be more useful if you convert them to a dictionary:
>>> results_dict = {v:k for k,v in results}
>>> print results_dict['111.111.5.6']
object6
>>> print results_dict['111.111.5.1']
object1
>>> print results_dict['blah']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'blah'
>>> print results_dict.get('111.111.5.5')
object5
>>> print results_dict.get('123456')
None
The usage is dict.get()
close to the syntax you asked for in your question.
The result is a tuple of tuples, so you can access it using indices 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 official Python docs
So your function might look like this:
def get_item(result, key):
for obj, num in result:
if num == key:
return obj, num
You can turn the input tuple into a dictionary and access those keys. Something like this (only tested in python 3, so you can make some changes to run with python 2.7)
from collections import defaultdict
mytuples = (('object1', '111.111.5.1'),
('object2', '111.111.5.1'),
('object3', '111.111.5.3'),
('object4', '111.111.5.4'),)
mydict = defaultdict(list)
for name, key in mytuples:
mydict[key].append(name)
for key, values in mydict.items():
print(key, values)
output:
111.111.5.1 ['object1', 'object2']
111.111.5.3 ['object3']
111.111.5.4 ['object4']
If you are just trying to index into a tuple follow the mention of the answer. If you want to search by key
result.getItemWithKey('111.111.5.1')
then you can use dictionaries instead of tuples.
You can also reverse the elements of your tuple in the dict's sense:
test = ((1, 'R'), (2, 'K'))
values = {y: x for x, y in test}
values['R']
1