我想进一步解释以下代码为何打印键的值。我正在为课程学习Python,而Zybooks的解释很糟糕。
# Complete the function to return a dictionary value
# if it exists or return Not Found if it doesn't exist
def findDictItem(mydict, key):
# Student code goes here
if key in mydict:
return (mydict[key])
else:
return 'Not Found'
# expected output: yellow
print(findDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: Not Found
print(findDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))
根据我的理解,return(mydict[key])
应该返回键而不是值,而是返回键值。
请问清楚吗?
答案 0 :(得分:1)
如果只想打印键或值,则可以使用类似的内容。
uploadfileAWSS3(fileuploadurl: string, file: File): Observable<HttpEvent<{}>> {
this.http = new HttpClient(this.handler); // to reset the header
const headers = new HttpHeaders({ 'Content-Type': file.type });
const req = new HttpRequest('PUT', fileuploadurl, file, { headers: headers, reportProgress: true })
return this.http.request(req)
}
如果您想要按键,只需将代码更改为
a = {'tomato': 'red', 'banana': 'yellow', 'lime': 'green'}
for key,value in a:
print (key) #will print keys : tomato, banana, lime
print (value) #will print values : red, yellow, green
print (a[key]) #will print values : red, yellow, green
此外,您可以进一步简化代码。
if key in mydict:
return key
else:
return 'Not Found'
我将您的代码重写如下:
return (key) if key in mydict else 'Not Found'
输出:
def findDictItem(mydict, key):
# Student code goes here
return key if key in mydict else 'Not Found'
# expected output: yellow
print(findDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: Not Found
print(findDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))
答案 1 :(得分:1)
仅举一个例子,有一个字典函数get,如果键不在字典中,该函数将返回默认值。
# Complete the function to return a dictionary value
# if it exists or return Not Found if it doesn't exist
def findDictItem(mydict, key):
return mydict.get(key, 'Not found')
答案 2 :(得分:0)
请记住,字典是键到值的映射,例如
{
'Ireland': 'Dublin',
'Indonesia': 'Jakarta'
# ^key ^value
}
mydict[key]
返回索引为key
的字典的值。如果您希望将dict的值设置为某个键,则可以使用mydict[key]
,因此mydict['Ireland']
将返回Dublin
。
如果您只想返回Dublin
,则可以使用return key