大家好,因为我的大学不提供编程领域的导师,因为这是第一个提供这个课程的学期。作业是:
编写一个程序:
是dict假设从
填充的文本文件的示例D1,Tyrannasaurous
D2,Apatasauros
D3,迅猛
D4,Tricerotops
D5,翼龙
T1,柴电
T2,蒸汽机
T3,Box Car
到目前为止我得到的是:
**
fin=open('C:/Python34/Lib/toys.txt','r')
print(fin)
toylookup=dict() #creates a dictionary named toy lookup
def get_line(): #get a single line from the file
newline=fin.readline() #get the line
newline=newline.strip() #strip away extra characters
return newline
print ('please enter toy code here>>>')
search_toy_code= input()
for toy_code in toylookup.keys():
if toy_code == search_toy_code:
print('The toy for that code is a','value')
else:
print("toy code not found")
**
说实话,我甚至不确定我对自己拥有的是什么。任何帮助都会非常感谢谢谢。
答案 0 :(得分:0)
有两个问题。
尝试迭代key
:value
对,如下所示:
for code, toy in toylookup.items():
if key == search_toy_code:
print('The toy for that code ({}) is a {}'.format(code, toy))
else:
print("Toy code ({}) not found".format(code))
查看dict.items()的文档:
<强>项()强>:
返回字典项目((键,值)对的新视图。)
答案 1 :(得分:0)
你应该熟悉基本的python编程。为了解决这些任务,您需要了解基本数据结构和循环。
# define path and name of file
filepath = "test.txt" # content like: B1,Baseball B2,Basketball B3,Football
# read file data
with open(filepath) as f:
fdata = f.readlines() # reads every line in fdata
# fdata is now a list containing each line
# prompt the user
print("please enter toy code here: ")
user_toy_code = input()
# dict container
toys_dict = {}
# get the items with toy codes and names
for line in fdata: # iterate over every line
line = line.strip() # remove extra whitespaces and stuff
line = line.split(" ") # splits "B1,Baseball B2,Basketball"
# to ["B1,Baseball", "B2,Basketball"]
for item in line: # iterate over the items of a line
item = item.split(",") # splits "B1,Baseball"
# to ["B1", "Baseball"]
toys_dict[item[0]] = item[1] # saves {"B1": "Baseball"} to the dict
# check if the user toy code is in our dict
if user_toy_code in toys_dict:
print("The toy for toy code {} is: {}".format(user_toy_code, toys_dict[user_toy_code]))
else:
print("Toy code {} not found".format(user_toy_code))