0

I have a dictionary that looks like this:

features = {"CAMERA": ['cam', 'Cam', 'camera', 'cameras', 'kameras', 'kamras'], "BATTERY": ['batterie', 'battery']}

I want to check whether a certain value is present inside any of those values or not. If yes, I want to return the key. How can I do so?

For example:

If 'karmas' is in features, I want to obtain the key 'CAMERA'.

  • 1
    Just loop over dict items: `[key for key, val_list in features.items() if 'kamras' in val_list ]` Having said that, if this is your typical use pattern, you have the key/values backward. – Mark Nov 10 '20 at 17:26
  • bad usage of dictionary - they are good if yo uwant to lookup a value for a key, to find the key by a value you need to iterate it until found or not found. Would be better to have a dictionary `{"cam":"CAMERA", "camera":"CAMERA", ...}` – Patrick Artner Nov 10 '20 at 17:26
  • 1
    It would be better if you inverted the dictionary: `{'cam': 'CAMERA', 'kamras': 'CAMERA', ...}` – Barmar Nov 10 '20 at 17:27
  • how would that help? @Barmar –  Nov 10 '20 at 17:28
  • Because you can immediately look up the item in constant time: `features['kamras']`, which is much more efficient. – Mark Nov 10 '20 at 17:29

1 Answers1

0

As mentioned in other answers, what you're asking for can be solved by looping over features and checking if the desired string is in any of the lists. For instance:

def get_keys(features, value):
    return tuple(
        k
        for k, values in features.items()
        if value in values
    )

print(get_keys(features, 'kamras')) # prints ("CAMERA",)

Or, if you want a single key, get_keys(features, 'kamras')[0].

However, if you're going to do this often, it would be better to invert your dictionary beforehand creating a new inverted dict:

inverted = {
    value: key
    for key, values in features.items()
    for value in values
}

print(inverted) # prints {'cam': 'CAMERA', 'Cam': 'CAMERA', 'camera': 'CAMERA', 'cameras': 'CAMERA', 'kameras': 'CAMERA', 'kamras': 'CAMERA', 'batterie': 'BATTERY', 'battery': 'BATTERY'}

This way, you can simply write:

print(inverted['kamra']) # prints "CAMERA"
ruancomelli
  • 610
  • 8
  • 17