[Python] A data-structure for 1:1 mappings in python?

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a problem which requires a reversable 1:1 mapping of keys to values.

    That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.

    x = D[y]
    y == D.inverse[x]


    The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, there's a recipe here but for a large dictionary it can be very slow.

    The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict.

    So is there a better structure I can use?

    • My application requires that this should be very fast and use as little as possible memory.
    • The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)
    • We can guarantee that either the key or the value (or both) will be an integer
    • It's likely that the structure will be needed to store thousands or possibly millions of items.
    • Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]

    Continue reading...

Compartilhe esta Página