Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 264
Black Knight Avatar asked Apr 06 '17 04:04

Black Knight


1 Answers

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! :)

like image 155
bharadhwaj Avatar answered Sep 29 '22 02:09

bharadhwaj