I am trying to work with a dictionary with tuples of n values as keys. I want to find tuples whose 2nd value is 10 (for example)
('HI', '10', '10', '10', '10', '10000', 'true', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10', '10', '10', '100', 'false', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10', '10', '10', '1000', 'true', '0.7GiB', '8', '1000s', '100MiB')
Any ideads how I can do it? THanks!
For that particular scenario, you'd have to iterate over all of the keys and test them against your predicate:
results = set(k for k in your_dict if k[1] == '10')
If you wanted to do this more quickly for repeated lookups and you knew ahead of time what field(s) you'd be checking, you could build indices that map between values for a particular index in each tuple to the keys that have a given value:
from collections import defaultdict
index_2nd = defaultdict(set)
for k in your_dict:
index_2nd[k[1]].add(k)
And then you could just use that to look up a particular value:
results = index_2nd['10']
You can't, not easily. You'd have to loop through all keys to check for those that match:
matching = [key for key in yourtupledict if key[1] == '10']
If you need to do this a lot in your application, you'd be better off creating indices; dictionaries or similar that map the second value in all your keys to specific keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With