我有下面的功能,我期望返回带有键并具有多个值的字典。下面的代码有什么问题?
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'}
我期待一本字典作为回报
{' ZOO ':'BEAR','MONKEY','MULE',' JUNGLE ':'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']}
这不正是你想要的东西,但它是什么蟒蛇允许的。
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras