Jguy
Jguy

Reputation: 580

python check if str is in a list of objects

I have a class. In short, to initialize you have to provide it with some values when you create it:

class Silo:

  def __init__(self, id, name, netid, node):
    self.id = id
    self.name = name
    self.node = node
    self.netid = netid

I may have more than one Silo and they are dynamically created by way of an sqllite database. For clarity's sake I've forgone the code for the database queries and instead printed the list of silos below in my example:

global siloList # siloList is a list of the Silos objects.
siloList = {} # Initialize
print(silos) # return: [(1, 'Silo 1', 1, 1), (2, 'Silo 2', 1, 4)]
for silo in silos: # loop through silos for each silo
  newSilo = Silo(silo[0], silo[1], silo[2], silo[3]) # Create the object from Silo class
  siloList[silo[0]] = newSilo # Create a list for each Silo object with the ID as the index

I would like to retrieve the ID for each object based on the name I enter so that I can do things with that class.

For example:

userInput = "Silo 2"
# Obtain "2" based on input "Silo 2" somehow
siloList[2].netid = 9 # Change the netid with siloList[id]

I can't figure out how to obtain the id of that object from a name appearing in it, though.

I found a silo = next((x for x, obj in enumerate(siloList) if obj['name'] == userInput), None) but this gives me an error TypeError: 'int' object is not subscriptable and I can't quite figure out how to make it work for my needs (or even if it will work or whatelse would be better).

Thanks.

Upvotes: 0

Views: 70

Answers (1)

jpeg
jpeg

Reputation: 2461

You can get a list of the matching Silo's IDs with

matching_silo_ID_list = list(id_ for id_ in siloList if siloList[id_].name == userInput)  

If you are sure that the matching list has exactly one element you can then safely use

matching_ID = matching_silo_ID_list[0]

to do

siloList[matching_ID].netid = 9

NB. I guess your siloList = {} is actually a dictionary.

Upvotes: 1

Related Questions