I have a dictionary self.indexList = {} filled with 3-item-lists values = [lineId, nominalLineId, vertex] for each dictionary key (its a supplement to a QgsSpatialIndex in PyQGIS, btw).

I need to reverse-search this dictionary for matching tuples of lineId and vertex. This function is the dealbreaker in a larger PyQGIS algorithm; called multiple times (almost 40.000 with a large test dataset) and causing 2/3 of total running time.

def get_idx_from_values(instance, lineID, vertex):
    """Searches the indexList for a lineID and a vertex number (= unique line segment).
    Returns dic index (=fid)."""
    items = instance.indexList.items()
    for idx, values in items:
        if values[0] == lineID and values[2] == vertex:
            return idx
    print("No index entry found for line " + str(lineID) + ", Vertex " + str(vertex))
    return None

I already found Search in a big dictionary Python where a second dictionary with a reversion of key and value is suggested.

I consider this, but I'm open for other suggestions how to speed up the code above, as my case - matching two values with a certain key - adds complexity to the simple key/value reversion.

up vote 1 down vote accepted

Tuples can be used as dictionary keys, so creating a second dictionary for reverse lookups can be as simple as:

reverse_lookup = {(lineID, vertex): idx 
                  for idx, (lineId, _, vertex) 
                  in instance.indexList.items()}
  • That's it! Nothing more to add. Thx. – fuzzysolutions Oct 8 at 13:32

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.