如何 return 在 python 中输出为具有唯一键和多个值的字典?

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

我有下面的函数,我期望 return 作为一个带键的字典并且有多个 values.what 在下面的代码中是错误的吗?

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 值:

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

而如果我打印

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

我希望有一本字典作为 return

{'动物园': 'BEAR','MONKEY','MULE','丛林 ': 'TIGER','ELEPHANT','HORSE'}

那时您可能希望值​​是一个数组。您可以通过更改一些代码行来做到这一点

from collections import defaultdict

   output = defaultdict(list)
   
   ...

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

结果:

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

这不完全你想要的,但这是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)
         ...