在字典和打印值中找到关键字

时间:2015-11-01 20:45:53

标签: python dictionary

大家好,因为我的大学不提供编程领域的导师,因为这是第一个提供这个课程的学期。作业是:

编写一个程序:

  1. 在一条有用的信息中打印出该代码的玩具名称,例如“该代码的玩具是棒球”
  2. 程序退出时,用户输入“退出”
  3. 而不是玩具代码 下面的

    是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")
    

    **

    说实话,我甚至不确定我对自己拥有的是什么。任何帮助都会非常感谢谢谢。

2 个答案:

答案 0 :(得分:0)

有两个问题。

  1. 你的字典没有填充;但是,目前您的问题中没有足够的信息来帮助解决该问题。需要知道文件的样子等。
  2. 您的查找循环不会显示匹配的键的值。以下是解决方案。
  3. 尝试迭代keyvalue对,如下所示:

    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))