Black Knight
Black Knight

Reputation: 71

Search for dictionary key when the keys are tuples

sample = {('red', 'blue', 'purple') : 'color', 'redo' : 'again', 'bred' : 'idk', 'greeting' : ('hi', 'hello')}

def search(c):
    if c in sample.keys():
        return sample[c]

print(search('red'))

This returns None. I know I can separate them and make multiple keys with the same value, but I'd really like to avoid doing so if I can. Can I?

And I would also like to be able to search for the values (which may be tuples as well) and get the corresponding keys.

Upvotes: 7

Views: 2845

Answers (2)

bharadhwaj
bharadhwaj

Reputation: 2139

Using iteritems() would help you here. Update your search() method as follows. Should work fine.

def search(c):
    for k, v in sample.iteritems():
        if type(k) in [list, tuple, dict] and c in k:
            return v
        elif c == k:
            return v

In case of multiple occurrences of c inside the dictionary,

def search(c):
    found = [ ]
    for k, v in sample.iteritems():
        if type(k) in [list, tuple, dict] and c in k:
            found.append(v)
        elif c == k:
           found.append(v)
    return found

This will return a list of matching values inside dictionary.


Hope this helps! :)

Upvotes: 5

donkopotamus
donkopotamus

Reputation: 23206

If you are not going to need to search by the whole tuple ('red', 'blue', 'purple') then just construct your dictionary a little differently perhaps:

sample = {e: v for k, v in {('red', 'blue', 'purple') : 'color'}.items()
               for e in k}

Upvotes: -1

Related Questions