python - O(1) lookup of single tuple element in a dict? -
i have structure in mind similar dict tuples keys, except can entries 1 of tuple elements.
e.g. (something similar this. not real python code, idea)
>>> d[(100, "apple")] = 5.0 # putting entry dict >>> d[(100, "pear")] = 10.0 # putting entry dict >>> d[(200, "pear")] = 10.0 # putting entry dict >>> d[100] # o(1) lookup [("apple", 5.0), ("pear", 10.0)] >>> d["pear"] # o(1) lookup [(100, 10.0), (200, 10.0)]
you can't defaultdict()
. best way in python, or best data structure use? i'd lookup o(1), dict.
in case, neither tuple element unique, nor values.
i considering:
- nested dicts
- two dicts?
- some database-like structure
consider like:
class mydict(object): def __init__(self): self._data = {} def __setitem__(self, key, val): self._data[key] = val if key[0] not in self._data: self._data[key[0]] = {} self._data[key[0]][key[1]] = val def __getitem__(self, key): return self._data[key]
this allows lookup tuple or first element, both in o(1)
. can implement same key[1]
. using dictionary of dictionaries makes subsequent lookup of other part of key o(1)
too. in use:
>>> d = mydict() >>> d[100, "apple"] = 5.0 >>> d[100, "pear"] = 10.0 >>> print d[100] {'pear': 10.0, 'apple': 5.0} >>> print d._data {(100, 'apple'): 5.0, (100, 'pear'): 10.0, 100: {'pear': 10.0, 'apple': 5.0}}
note assumes each combination key[0], key[1]
have single val
.
see e.g. how "perfectly" override dict? on making custom dictionaries.
Comments
Post a Comment