我有一个函数接受字典作为参数(从另一个有效的函数返回).这个函数应该要求输入一个字符串,并查看字典中的每个元素,看看它是否在那里.字典基本上是三字母缩写:国家即:AFG:阿富汗等等.如果我将'sta'作为我的字符串,它应该将任何具有该团队STATY,AfghaniSTAn,coSTA rica等片段的国家附加到初始化的空列表中,然后返回所述列表.否则,它返回[未找到].返回列表应如下所示:[['Code','Country'],['USA','United States'],['CRI','Costa Rica'],['AFG','Afganistan']]这是我的代码到目前为止的样子:
def findCode(countries):
some_strng = input("Give me a country to search for using a three letter acronym: ")
reference =['Code','Country']
code_country= [reference]
for key in countries:
if some_strng in countries:
code_country.append([key,countries[key]])
if not(some_strng in countries):
code_country.append( ['NOT FOUND'])
print (code_country)
return code_country
Run Code Online (Sandbox Code Playgroud)
我的代码一直在返回['找不到']
我有一个文本文件保存在记事本中,但移动到我的python文件夹,左边有一个国家的三个字母的缩写词,然后右边有四到五个空格,它有一个与之对应的国家:
AFG阿富汗
ARM亚美尼亚
等
我需要字典使用三个字母作为关键,而国家是价值.它有每个参加奥运会的国家.这是我的代码到目前为止的样子:
def country(fileName):
infile = open(fileName,'r')
countryDict = {}
for line in infile:
key,value = line.split()
countryDict[key] = value
print(countryDict)
return countryDict
country('CountryCodes.txt')
Run Code Online (Sandbox Code Playgroud) 给定字典 d 和列表 lst,从字典中删除所有键是 lst 元素的元素。列表中任何不是字典键的元素都应该添加到与变量 not_found 关联的新集合中。例如,给定字典 {1:2, 3:4, 5:6, 7:8} 和列表 [1, 6, 7],结果字典将是 {3:4, 5:6} 和set not_found 将包含 6。
这是我的代码的样子:
not_found = ()
for i in d:
if d[i] in lst:
not_found.append(d[i])
del d[i]
Run Code Online (Sandbox Code Playgroud)