繁体   English   中英

在字典中查找键并打印值

[英]find key in dictionary and print value

大家好,我被困在课堂作业上,现在不知道该去哪里,因为我的大学不提供编程领域的导师,因为这是提供的第一个学期。 分配是:

编写一个程序:

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

下面是 dict 应该从中填充的文本文件的示例

D1,霸王龙

D2,阿帕塔龙

D3,迅猛龙

D4,三角龙

D5,翼手龙

T1,柴电

T2,蒸汽机

T3,厢式车

到目前为止我得到的是:

**

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

**

老实说,我什至不确定我对我所拥有的是否正确。 任何帮助都将不胜感激,谢谢。

有两个问题。

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

尝试像这样迭代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()的文档:

项目()

返回字典项((键,值)对)的新视图。

您应该熟悉基本的 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM