【发布时间】:2020-08-20 17:44:42
【问题描述】:
我有一个嵌套字典,其中显示每个 MLB 运动队的分区,分区是键,值是该分区中的球队。每个键将有大约 5 个值。我需要做的是反向映射它,以便我能够返回给定团队的部门。
Divisions_dict = {
'ALCentral' : ['Chicago White Sox' , 'Cleveland Indians' , 'Detroit Tigers' , 'Minnesota Twins' , 'Kansas City Royals'] ,
'ALEast' : ['New York Yankees' , 'Boston Red Sox', 'Tampa Bay Rays' , 'Toronto Blue Jays' , 'Baltimore Orioles'],
'Comeon' : 'hello'
}
def get_key(val):
for key, value in Divisions_dict.items():
if val == value:
return key
return "key doesn't exist"
print(get_key('hello'))
print(get_key('Toronto Blue Jays'))
我知道我做错了,我认为这与团队在字典中的列表形式有关。 This is the code I have tried but to no avail。当我运行程序时,它会打印第一行,但是当我要求它打印"Toronto Blue Jays" 的密钥时,它会返回"key doesn't exist"。任何帮助将不胜感激!
【问题讨论】:
标签: python python-3.x dictionary nested key-value