mik
mik

Reputation: 356

Create a dictionary with "optional keys"

I am generating a solution for geographical data. This involves one ID for each specific location - a key - and also a coordinate pair - also a key - for a specific value.

Depending on the methods I have implemented, it would be nice to access the objects based on ID or coordinates. One workaround for this would be pointing one the of the keys to the other one.

d = dict()
for i in range(100):
    d[i] = i
    d[str(i) + '_aux'] = d[i]
print(d[1], d['1_aux']

I don't enjoy having "duplicate" keys for the same value. Is there a pythonic way to replicate this functionality?

Upvotes: 0

Views: 828

Answers (2)

martineau
martineau

Reputation: 123501

In Python 3.3+ you can use a collections.ChainMap to implement your own dictionary-like class as shown below. Additional dictionary-like methods could be implemented as needed.

from collections import ChainMap

class AuxDict:
    @staticmethod
    def aux_key(key):
        return str(key) + '_aux'

    def __init__(self):
        self._mapping, self._aux_mapping = {}, {}
        self._chainmap = ChainMap(self._mapping, self._aux_mapping)

    def __getitem__(self, key):
        return self._chainmap.__getitem__(key)

    def __setitem__(self, key, value):
        self._mapping.__setitem__(key, value)
        self._aux_mapping.__setitem__(self.aux_key(key), value)


d = AuxDict()
for i in range(10):
    d[i] = i
print(d[1], d['1_aux'])  # -> 1 1
print(d[2], d['2_aux'])  # -> 2 2
# etc...

Upvotes: 1

Jussi Nurminen
Jussi Nurminen

Reputation: 2408

I don't see any problem with creating multiple keys, if multiple keys are what you want. An alternative approach would be a function that would translate coordinates to IDs. Then you could do:

locations = dict()

def coord_to_ID(coords):
    # insert suitable code here

locations[coord_to_ID(coords)]

Upvotes: 2

Related Questions