I have a structure in mind that is similar to a dict with tuples as keys, except you can look up entries with only one of the tuple elements.
e.g. (something similar to this. not real Python code, just an idea)
>>> d[(100, "apple")] = 5.0 # putting entry into dict
>>> d[(100, "pear")] = 10.0 # putting entry into dict
>>> d[(200, "pear")] = 10.0 # putting entry into 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 currently do this with a defaultdict()
. What is the best way to do this in Python, or the best data structure to use? I'd like the lookup to be O(1), like it is for a dict.
In this case, neither tuple element will be unique, nor will the values.
I am considering:
- Nested dicts
- Two dicts?
- Some database-like structure