Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tuple as a dictionary key in Python

Tags:

python

tuples

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!

like image 706
Yotam Avatar asked Dec 04 '22 02:12

Yotam


2 Answers

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']
like image 154
Amber Avatar answered Dec 15 '22 14:12

Amber


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.

like image 38
Martijn Pieters Avatar answered Dec 15 '22 13:12

Martijn Pieters