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.


1 Answer 1


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()}
  • \$\begingroup\$ That's it! Nothing more to add. Thx. \$\endgroup\$ Commented Oct 8, 2018 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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