Search for a dictionary key when 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'))

It returns None. I know that I can separate them and make several keys with the same value, but I would really like me not to do this if I can. Can I?

And I would also like to be able to look up values ​​(which can also be tuples) and get the corresponding keys.

+4
source share
3 answers

Use iteritems()will help you here. Update the method search()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 the case of multiple entries cwithin 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 the dictionary.


Hope this helps! :)

0

:

def search_keys(dictionary, searchstring):
    try:
        return dictionary[searchstring]
    except KeyError:
        for key in dictionary:
            if not isinstance(key, str) and searchstring in key:
                return dictionary[key]
    return None

:

, searchstring dictionary. , , searchstring ( ). : . , , KeyError, ,

if searchstring in dictionary: 
    return dictionary[searchstring]
else:
    ...

, searchstring . , , , : win-win.

except , , ( in 'red' to 'redo', , ), , searchstring .


. , , , -, , - . .

, , , . , , , , , , . .

-1

If you don’t need to search the entire tuple ('red', 'blue', 'purple'), then just build your dictionary a little differently:

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

Source: https://habr.com/ru/post/1674160/


All Articles