Multivalued search in dictionary keys

Iterating over bit values - on this subject:

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 an idea I'm trying to achieve, how to take a key and find n values ​​in a key, and then return the key if the values ​​are in the key

+6
source share
3 answers

Below, the bla method returns the database key if x and y correspond to the first and second elements of the tuple (of any length), respectively, which 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 bla method 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 
+3
source

Since you said “return the key” in the question, I assume that you really want to isolate the keys in the dictionary whose values ​​correspond to a certain set of search parameters (the code fragment that you posted returns the values, not the keys). Assuming self.Database is a dictionary, you can extract the keys as a list comprehension using 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 map specific positions in a tuple, the conditional inside the understanding can be changed to something like if x == self.Database[i][1] and y == self.Database[i][2] .

If you do not have the keys, ask your question.

+2
source

You can use the built-in map() to set the variables x and y .

 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 to use items() , you can do the following (equivalently):

 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 another way to do this without map() , it gives you the advantage of unpacking tuples when iterating over a dict:

  def bla(self,x,y): for key, (x, y) in self.DataBase.items(): if x == dept and y == year: return key 

You can also write above, since using list comprehension, although I would say that 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 steps for Python 3, which I assume, are what you want as one of your Python 3.x tags

+1
source

Source: https://habr.com/ru/post/980410/


All Articles