How to return output as a dictionary with unique key and multiple values in python?

Viewed 49

I have below function where I am expecting the return as a dictionary with key and having multiple values.what is wrong in below code?

def get_list_animals():
        output = {}
        animal_house = ['ZOO','JUNGLE']
        connection = Connection("WORLD")
        cursor = connection.cursor()
        for house in animal_house:
            statement = """select animals from inventory where place = '{}'""".format(house.upper())
            cursor.execute(statement)
            rows = cursor.fetchall()
            for row in rows:
                values = str(row).strip('()')
                if house == 'ZOO' or 'JUNGLE':
                    output[house] = values
                    #print(output)
        return output
    
    answer = get_list_animals()
    print(answer)

Return value:

{'ZOO': 'GOAT', 'JUNGLE': 'HORSE'}

whereas I am getting lots of values for both ZOO & JUNGLE in below way if I print

ZOO:
    {'ZOO': 'BEAR'}
    {'ZOO': 'MONKEY'}
    {'ZOO': 'MULE'}
JUNGLE:
    {'ZOO': 'MULE', 'JUNGLE': 'TIGER'}
    {'ZOO': 'MULE', 'JUNGLE': 'ELEPHANT'}
    {'ZOO': 'MULE', 'JUNGLE': 'HORSE'}

I am expecting a single dictionary as a return

{'ZOO': 'BEAR','MONKEY','MULE','JUNGLE': 'TIGER','ELEPHANT','HORSE'}

2 Answers

You'll probably want the value to be an array then. You can do so by changing some of your lines of code

from collections import defaultdict

   output = defaultdict(list)
   
   ...

   if house == 'ZOO' or 'JUNGLE':
        output[house].append(values)

Result:

{'ZOO': ['BEAR','MONKEY','MULE'],'JUNGLE': ['TIGER','ELEPHANT','HORSE']}

It's not exactly what you wanted, but it's what is allowed by python.

def get_list_animals():
        animal_house = ['ZOO','JUNGLE']

        # initialize values of the dictionary as lists 
        output = {i:[] for i in animal_house}

         ...
                # append to the list
                if house == 'ZOO' or 'JUNGLE':
                    output[house].append(values)
         ...

     
Related