繁体   English   中英

如何在 python 中将 output 作为具有唯一键和多个值的字典返回?

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

我有下面的 function 我期望返回作为带有键和多个值的字典。下面的代码有什么问题?

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)

返回值:

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

而如果我打印,我会以下面的方式为 ZOO 和 JUNGLE 获得很多价值

ZOO:
    {'ZOO': 'BEAR'}
    {'ZOO': 'MONKEY'}
    {'ZOO': 'MULE'}
JUNGLE:
    {'ZOO': 'MULE', 'JUNGLE': 'TIGER'}
    {'ZOO': 'MULE', 'JUNGLE': 'ELEPHANT'}
    {'ZOO': 'MULE', 'JUNGLE': '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)
         ...

     

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM