[英]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.