我正在尝试创建一个字典,使用调用函数'findPokemonInfo(name)'并遍历我的csv文件并以这种格式返回信息:
攻击:49
capture_rate: 45
名称:Bulbasaur
速度:45
类型:草
csv文件显示如下:name,type,attack,speed,capture_rate
这是我目前拥有的:
def findPokemonInfo(name):
import csv
myFile = open('pokemon.csv',"r")
csvReader = csv.reader(myFile,delimiter=",")
next(csvReader)
pokeMon = {}
for row in csvReader:
if (row[0] == name):
pokeMon[row[0]] = {'attack':row[2], 'capture_rate':row[4], 'name':row[0], 'speed':row[3], 'type':row[1]}
print (pokeMon)
返回:
findPokemonInfo (Bulbasaur)
{'Bulbasaur': {'attack': '49', 'capture_rate': '45', 'name': 'Bulbasaur', 'speed': '45', 'type': 'grass'}}
这样打印你的字典:
d = {'Bulbasaur': {'attack': '49', 'capture_rate': '45', 'name': 'Bulbasaur', 'speed': '45', 'type': 'grass'}}
for key in d:
for sub_key in d[key]:
print(sub_key,": ", d[key][sub_key])
输出如下:
attack : 49
capture_rate : 45
name : Bulbasaur
speed : 45
type : grass