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