A data-structure for 1:1 mappings in python?

前端 未结 8 1506
广开言路
广开言路 2020-12-17 08:17

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

8条回答
  •  旧巷少年郎
    2020-12-17 08:30

    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.

    Not really. Have you measured that? Since both dictionaries would use references to the same objects as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than twice and is a fixed ammount regardless of your data size.

    What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory.

    Example:

    a = "some really really big text spending a lot of memory"
    
    number_to_text = {1: a}
    text_to_number = {a: 1}
    

    Only a single copy of the "really big" string exists, so you end up spending just a little more memory. That's generally affordable.

    I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend at least enough memory to store a reverse lookup hash table (which is exactly what's being done in your "unite two dicts" solution).

提交回复
热议问题