[英]Checking for match between user input and dictionary key with multiple values
If I want to check if the inputted parameter in the checkPlayer
function matches a key in dict1
and return the entire object or a specific value for the respective key, how would I change this code? 如果我要检查,如果在输入参数
checkPlayer
功能相匹配的关键dict1
并返回整个对象或特定值相应的键,我将如何改变这种代码?
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def checkPlayer(plyr):
for x in dict1:
if plyr == x:
print(x)
checkPlayer('Messi')
I am mainly confused as to why printing x
would print the players name and not the whole object. 我很困惑为什么打印
x
会打印玩家名字而不是整个对象。 How would I print the whole object , or more specifically, just the nationality or team if a match was found. 我将如何打印整个对象 ,或者更具体地说, 只是国籍或团队,如果找到匹配。 Not quite sure how to access indexes in dictionaries using for loops, it's not quite as intuitive as lists :/
不太确定如何使用for循环访问字典中的索引,它不像列表那样直观:/
Thanks guys 多谢你们
You are iterating over the keys of the dictionary and printing the key (which is the name of the player) if it was found. 您正在迭代字典的键并打印密钥 (这是播放器的名称),如果找到它。 To get the value for that key, you can use the
get
method (which also allows you to specify a default if a key wasn't found in the dictionary): 要获取该键的值,可以使用
get
方法(如果在字典中找不到键,还可以指定默认值):
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def checkPlayer(plyr):
print(dict1.get(plyr))
checkPlayer('Messi')
Output 产量
('Argentina', 'Barcelona')
Furthermore, to check if a player name is in your dictionary, you can simply have if plyr in dict1
; 此外,要检查一个玩家名字是否在你的字典中,你可以简单地
if plyr in dict1
; you don't need to iterate over all the keys. 你不需要迭代所有键。 So your method can also be:
所以你的方法也可以是:
def checkPlayer(plyr):
if plyr in dict1:
print(plyr, dict1[plyr][1])
checkPlayer('Messi')
Output 产量
Messi Barcelona
your object is a key:value the key is 'Messi' the value is 'Argentina','Barcelona' however in your print statement you only print the name of object will will return the key only without the value 你的对象是一个关键:值键是'Messi',值是'Argentina','Barcelona'但是在你的print语句中你只打印对象的名称将只返回没有值的键
to access the value you may use get() or the index of the object inside your dictionary 访问您可能使用的值get()或字典中对象的索引
to get your desire result use this : 得到你想要的结果使用这个:
print plyr,':',dict1[plyr]
You can use below code: 您可以使用以下代码:
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
checkPlayer = 'Messi'
print (dict1.get(checkPlayer,'Player not found')) # 'Player not found' will be returned if checkPLayer is not in the dict1.keys()
#result --> ('Argentina', 'Barcelona')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.