Reputation: 443
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
Upvotes: 6
Views: 3291
Reputation: 9427
You may use the built-in map()
to set the x
and y
variables.
def bla(self,x,y) :
for key in self.DataBase :
x,y = map(float, self.DataBase[key])
if x == dept and y == year:
return key
If you prefer using items()
, you may do the following as well (equally valid):
def bla(self,x,y):
for key, val in self.DataBase.items():
x, y = map(float, val)
if x == dept and y == year:
return key
Here's yet another way of doing it without map()
, this gives you the advantage of unpacking the tuples while iterating over the dict:
def bla(self,x,y):
for key, (x, y) in self.DataBase.items():
if x == dept and y == year:
return key
You may also write the above as so, using list comprehension, although I would say the one above is preferable:
def bla(self,x,y):
found = {key for key, (x, y) in self.DataBase.items() if x==dept and y==year}
found = ''.join(num) #joins set into string
return found
The following all work for Python 3, which I assume is what you want since one of your tags are Python 3.x
Upvotes: 1
Reputation: 1488
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
Upvotes: 3
Reputation: 5236
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.
Upvotes: 2