I have some dozens of tuples each containing 2 strings and 1 integer. Ex:(str, str, int).
All these tuples are in a list (example below).
Each tuple is unique and each tuple’s strings and integer are also unique.
Ex.:
[('a','aA', 53),
('b','bb', 21),
('c','cc', 234),
('d','de', 76),
..]
What I want is, to use this data structure like a dictionary and retrieve the entire tuple for any of one of the 3 values I pass.
Ex.:
For value
'a'-> get the whole tuple of:('a', 'aA', 53)For value
'cc'-> get the whole tuple of:('c', 'cc', 234)For value
'76'– > get the whole tuple of:('d', 'de', 76)
So far I have done:
Creating a simple function to iterate through the list of tuples, go through each tuple and its all 3 values to find a match and if there’s a match return the tuple, if not return False.
This sounds slow and seems like the very wrong way to do this task.
- What would be the right way to achieve this?
- Should I create 3 dictionaries and link them to each other?
You’d have to create separate indexes using dictionaries to allow looking up elements by contents:
Now you can look up indices on strings:
Note that this always returns a list, as your entries could match multiple tuples. If the lookup is a string, we only use the first two indexes, otherwise only the 3rd.
Alternatively, the more general solution that doesn’t care about entry type, would be to create a list of indexes, instead of 3 separate variables:
with the lookup becoming:
You could bundle this all up in a class, where your indexes are kept up to date as you add or remove elements.