Iterating over dict values - related to this question:
def bla(self,x,y)
for i in self.DataBase.keys():
for x,y in self.DataBase[i]:
if x == dept and y == year:
return self.DataBase[i]
This is more of the idea that I am trying to achieve, how do I take a key and search for n values in the key, then return the key if the values are in the key
Below, the method bla
returns the database key if x and y match the first and second elements of the tuple (of whatever length), respectively, that correspond to the key:
def bla(self, x, y)
for key, value in self.DataBase.iteritems():
if (x, y) == value[:2]:
return key
And now below, the method bla
returns the database key if the database value which is a tuple contains both x and y:
def bla(self, x, y)
for key, value in self.DataBase.iteritems():
if x in value and y in value:
return key
Since you said "return the key" in the question, I assume you actually want to isolate the keys in the dictionary whose values match some set of search parameters (the code fragment you posted returns the values, not the keys). Assuming self.Database
is a dictionary, you could extract the keys as a list comprehension with something like the following:
def getMatchingKeys(self, x, y):
'''Extract keys whose values contain x and y (position does not matter)'''
return [i for i in self.Database if x in self.Database[i] and y in self.Database[i]]
Keys whose values contain both x and y anywhere in the tuple will be returned. If you need to match specific positions in the tuple, the conditional inside the comprehension can be changed to something like if x == self.Database[i][1] and y == self.Database[i][2]
.
If you aren't after the keys, please clarify your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With