Home > Software engineering >  How to Create a Python Program that Outputs a Specific Key Value from a Python Dictionary that has M
How to Create a Python Program that Outputs a Specific Key Value from a Python Dictionary that has M

Time:06-15

I have a Python dictionary with multiple keys with its specific values:

animal_dict =
{'Animal':
   {0: 'Giraffe',
    1: 'Kangaroo',
    2: 'Koala',
    3: 'Lion',
    4: 'Walrus'},
 'ID Number':
   {0: '121',
    1: '234',
    2: '673',
    3: '543',
    4: '134'},
 'Zoo Location':
   {0: 'Chicago',
    1: 'New York',
    2: 'Seattle',
    3: 'Tulsa',
    4: 'Santa Monica'},
 }

I need to figure out how to create a program that will take an input of a name of one of the animals (a key), and then output an ID Number (value) that is specific to that animal (key). How can I execute this program, and specifically output the ID Number and not the Zoo Location?

What I'm trying to do is if the user enters the animal name, the program checks if it's in the dictionary and, if it is, it should show the information relating to that specific animal.

Here's what I have so far (not correct):

enter_animal_name = input("Enter Animal Name: ")
if enter_animal_name in animal_dict.values():
  print("Animal ID Number: "   animal_dict[enter_animal_name])
else:
  print("Animal does not exist in database")

Where am I going wrong? Thank you.

CodePudding user response:

You can achieve this using the following snippet of code

enter_animal_name = input("Enter Animal Name: ")

for key, value in animal_dict['Animal'].items():
    if value == enter_animal_name:
        print("Animal ID Number: ", animal_dict['ID Number'][key])
        break
else:
    print("Animal does not exist in database")

When the user input the animal name, it looks within the Animal sub dictionary. It compare every value one by one until it find the corresponding value, in which case, it will print the ID, using the key. When the id is found, the loop break as it's not necessary to continue iterating within the dictionary. If nothing have been found, the else statement of the for loop is executed.


However, i don't think you should store your data within nested dictionaries. Here is a rewrite proposition using a list of Animal dataclasses:

from dataclasses import dataclass


@dataclass
class Animal:
    id: int
    name: str
    zoo_location: str


animals = [
    Animal(id=0, name='Giraffe', zoo_location='Chicago'),
    Animal(id=1, name='Kangaroo', zoo_location='New York'),
    Animal(id=2, name='Koala', zoo_location='Seattle'),
    Animal(id=3, name='Lion', zoo_location='Tulsa'),
    Animal(id=4, name='Walrus', zoo_location='Santa Monica'),
]

enter_animal_name = input("Enter Animal Name: ")

for animal in animals:
    if animal.name == enter_animal_name:
        print("Animal ID Number: ", animal.id)
        break
else:
    print("Animal does not exist in database")

CodePudding user response:

There seems to be a lot of confusion reflected in your explanation of your data structure. Lets look at a slightly smaller version of your dict and I'll explain:

animal_dict = {
    'Animal': {
        0: 'Giraffe',
        1: 'Kangaroo',
    }
}

The one key in animal_dict is the string 'Animal'. It's value is the inner dict, {0: 'Giraffe', 1: 'Kangaroo'}. The animal names are in fact values in that inner dict (the numbers are the keys).

Dictionaries do not make it easy to search their values. They're designed for fast lookup of keys, but because your data is organized backwards, it's going to be inconvenient to do the searches you want. Not impossible, mind you, just a lot less efficient than you might expect from a dictionary-based datastructure.

A better approach might be to restructure your data, then do your search on the new structure. For instance, here's a dictionary comprehension that will build a new dictionary that maps directly from animal name to ID number:

good_mapping = {name: animal_dict['ID Number'][index]
                for index, name in animal_dict['Animal'].items()}

Your lookup code would then become:

name = input("Enter Animal Name: ")
if name in good_mapping:
    print("Animal ID Number: "   good_mapping[name])
else:
    print("Animal does not exist in database")
  • Related