Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through list of tupples and return matching tupple value in Django

I have been struggling with this for hours,
I have a variable :

numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)]

that makes me a list like this from my Model :

[(1, <CalculatedNumbers: one>), (2, <CalculatedNumbers: two>), (3, <CalculatedNumbers: three>), (4, <CalculatedNumbers: four>), ...]

and I have another variable :
‘usernobat’
that returns me a number

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I go through my list of tupples, find the matching tupple index that is matching ‘usernobat’ and return its data ?

I have tried for loops like this :

matching_object = None
    for obj in range(len(numbered_objects)):
        for key in numbered_objects[obj]:
            if key == usernobat:
                matching_object = key
                break 

but they all return None

edit: I added my entire view :



def cart_resault(request):
    carts = CalculatedNumbers.objects.filter(used=False)[:50]
    usersubmit = UserSelection.objects.get(user=request.user)

    usernobat, usernobat__created = UserNobats.objects.get_or_create(user=request.user)

    numbers_sum = sum(getattr(usersubmit, f'number_{i}', 0) for i in range(1, 11))
    usernobat.usernobat = numbers_sum
    usernobat.save()
    
    
    numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)]
    
    matching_object = None
    for obj in range(len(numbered_objects)):
        for key in numbered_objects[obj]:
            if key == usernobat:
                matching_object = key
                break 

>Solution :

I think your usernobat is probably still a string, so '2' for example, not 2, and thus 2 != '2'.

You can cast it to a 2 with int(…) first, so:

usernobat = int(usernobat)

matching_object = None
for k, v in numbered_objects:
    if k == usernobat:
        matching_object = v
        break
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading