Home > Software engineering >  How to make a python dictionary's output be vertical
How to make a python dictionary's output be vertical

Time:01-17

so the following is the code and what I'm trying to do here is I want the output of the code to be vertical

if I use the following code then the output would be like: cowsheepchickengoatpig

I want the output to be :

enter image description here





animaldictionary={

    "house pets":
    "cat"
    "dog"
    "bird"
    "hamster"
    "snake",

    "farm animals":
    "cow"
    "sheep"
    "chicken"
    "goat"
    "pig"
}

print(animaldictionary[input('enter the category:')])

I tried a for loop but it still shows the output horizonally

which is like: cowsheepchickengoatpig

CodePudding user response:

The values are just a single long string. This is probably not waht you want.

Use a list:

animaldictionary = {
    "house pets": [
        "cat",
        "dog",
        "bird",
        "hamster",
        "snake"
    ],
    "farm animals": [
        "cow",
        "sheep",
        "chicken",
        "goat",
        "pig"
    ]
}

Then to get the output in the way you wanted, you can use str.join with new line:

print('\n'.join(animaldictionary[input('enter the category:')]))

If you really do want the values to be a single string, you can use multilined strings then you will get the output you want with the code you already have but you will need to be careful with the tabs:

animaldictionary = {
    "house pets":
"""cat
dog
bird"
hamster"
    snake""",
    "farm animals":
    """cow
sheep
chicken
goat
pig"""
}

or manually add new lines (probably the worst "solution"):

animaldictionary = {
    "house pets":
    "cat\n"
    "dog\n"
    "bird\n"
    "hamster\n"
    "snake",

    "farm animals":
    "cow\n"
    "sheep\n"
    "chicken\n"
    "goat\n"
    "pig"
}

CodePudding user response:

I've got two versions of the answer.

  1. Use a function that prints a selected value of the dict vertically
  2. A custom class, that inherits all methods from a python dict class {}, and implements a custom behavior.

Both options return an output that you are looking for:

cow
sheep
chicken
goat
pig

Option 1. Using a vertical_print function

animaldictionary = {

    "house pets":
    ["cat",
     "dog",
     "bird",
     "hamster",
     "snake"],

    "farm animals":
    ["cow",
     "sheep",
     "chicken",
     "goat",
     "pig"]
}


def vertical_print(input_dict: dict, category: str):
    """prints a selected dict value vertically

    Args:
        input_dict (dict): dictionary
        category (str): key to select
    """
    print('\n'.join(input_dict.get(category, '')))


vertical_print(animaldictionary, 'farm animals')

Option 2. Using a class based on dict class

class VerticalPrintingDict(dict):
    """customized version based on the python dict, 
    will not return an item but a string that prints vertically

    Args:
        dict (class): base class that it inherits from
    """

    def __init__(self, *arg, **kw):
        """initilized using superclass
        """
        super(VerticalPrintingDict, self).__init__(*arg, **kw)

    def __getitem__(self, item) -> str:
        """impementation of a custom method []

        Args:
            item (str): key

        Returns:
            str: string, \n separated
        """
        return '\n'.join(super().__getitem__(item))


custom_dict = VerticalPrintingDict({

    "house pets":
    ["cat",
     "dog",
     "bird",
     "hamster",
     "snake"],

    "farm animals":
    ["cow",
     "sheep",
     "chicken",
     "goat",
     "pig"]
})
print(custom_dict['farm animals'])
  • Related