Yotam
Yotam

Reputation: 10485

Using tuple as a dictionary key in Python

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!

Upvotes: 4

Views: 22041

Answers (4)

zenpoy
zenpoy

Reputation: 20126

Use iterkeys() to iterate over keys

d = {(1,2,3):1,(1,2,4):2,(2,2,3):3}

for k in d.iterkeys():
    if k[0] == 1:
        print k

Upvotes: 2

Przemek Lewandowski
Przemek Lewandowski

Reputation: 516

def find(key_element):
    return [value for key, value in a.iteritems() if len(key) > 1 and key[1] == key_element]

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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.

Upvotes: 4

Amber
Amber

Reputation: 526573

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']

Upvotes: 10

Related Questions