Home > front end >  How can you check which value in a dictionary equals a userInput?
How can you check which value in a dictionary equals a userInput?

Time:12-16

var dict1 = {
"fish": "clams",
"fish": "clownfish",
"reptile": "alligator",
"reptile": "snake"


var userInput = prompt("Enter an animal");
If (userInput in dict1[0]) {
  alert ("its a fish");
} else if (userInput in dict1[2]) {
  alert ("its a reptile");
} else {
  alert("Key not found");
}

I don't want to know if the user input exists as a value in the dictionary. Instead, I want to know at which position/key. The goal of this program is to use only one dictionary and print the type of animal specified in the dictionary. By checking where the UserInput == the value.

var dict1 = {
  "fish":  "clams",
  "fish": "clownfish",
};
var dict2 = {
  "reptile":  "alligator",
  "reptile": "snake"
};
var userInput = prompt("Enter an animal");
If (userInput in dict1) {
  alert("its a fish");
} else if (userInput in dict2) {
  alert("its a reptile");
} else {
  alert("Key not found");
}

Currently, I have been using two dictionaries but I want to use only one.

CodePudding user response:

If you keep the dictionary this way, you will have to iterate over all keys and check the corresponding values equal to user input. This would result in a time complexity of linear order

And hence, no use of using a dictionary.

The simplest solution is to just invert the dictionary, meaning, make keys as values and values as keys.

Eg.

var dict = {
  "clams":  "fish",
  "clownfish": "fish",
  "alligator":  "reptile",
  "snake": "reptile"
};

and then check on the input,

if(!dict[userInput]){
    
    alert("Key not found");
}else{
    // whatever
}

Thank you...

CodePudding user response:

Ultimately it depends how you want to group your animal species. Ritupana's answer is good because it allows you easy access to the animals and their species just by using the object key.

In this example I've used your species as a key but placed the animals in an array. You can then iterate over the dictionary to find if an animal is included in that array.

const animals = {
  mollusc: ['clam'],
  fish: ['cod', 'clownfish'],
  reptile: ['snake', 'alligator'],
  mammal: ['whale', 'human', 'cow'],
  bird: ['crow', 'pigeon']
};

const userInput = prompt('Enter an animal');

function match(input, dict) {
  for (const key in dict) {
    const found = dict[key].includes(input);
    if (found) return `A ${input} is a ${key}.`;
  }
  return 'No matching animal';
}

console.log(match(userInput, animals));

Additional documentation

  • Related