不确定我在做什么错。我以为zip方法可以检查一个值是否在多个列表中?我希望它执行的操作是检查该值是否在那些词典中的任何一个中,如果是,则打印其键,但如果不是,则仅打印一个字符串(“不在任何词典中”)。此方法出于某些原因会用实际字典打印其中的40个。
MLB_Teams = {1: 'New York Yankees', 2: 'Pittsburgh Pirates'}
NBA_Teams = {1: 'Houston Rockets', 2: 'Brooklyn Nets'}
NFL_Teams = {1: 'Philadelphia Eagles', 2: 'Detroit Lions'}
for (key,value), (key,value), (key, value) in zip(MLB_Teams.items(), NBA_Teams.items(), NFL_Teams.items()):
reply = 'Houston Rockets'
if reply == value:
print(key)
else:
print('Not In Any Dictionary')
答案 0 :(得分:0)
我认为您可以通过一种非常简单的方式做到这一点:
MLB_Teams = {1: 'New York Yankees', 2: 'Pittsburgh Pirates'}
NBA_Teams = {1: 'Houston Rockets', 2: 'Brooklyn Nets'}
NFL_Teams = {1: 'Philadelphia Eagles', 2: 'Detroit Lions'}
v = 'Philadelphia Eagles'
def find_in_dict(val, d):
for k, v in d.items():
if v == val:
print(k)
return True
for dd in (MLB_Teams, NBA_Teams, NFL_Teams):
if find_in_dict(v, dd):
break
else:
print('Not In Any Dictionary')
答案 1 :(得分:0)
问题在于您如何将变量名重用于键和值。添加打印语句以查看效果。
for (key,value), (key,value), (key, value) in zip(MLB_Teams.items(), NBA_Teams.items(), NFL_Teams.items()):
print(value) #added
reply = 'Houston Rockets'
if reply == value:
print(key)
else:
print('Not In Any Dictionary')
#output
Philadelphia Eagles
Not In Any Dictionary
Detroit Lions
Not In Any Dictionary
将变量键和值重新分配给元组中的最后一个条目。
如果稍后再处理包装,则可以使用zip。
MLB_Teams = {1: 'New York Yankees', 2: 'Pittsburgh Pirates'}
NBA_Teams = {1: 'Houston Rockets', 2: 'Brooklyn Nets'}
NFL_Teams = {1: 'Philadelphia Eagles', 2: 'Detroit Lions'}
reply = 'Houston Rockets'
for tups in zip(MLB_Teams.items(), NBA_Teams.items(), NFL_Teams.items()):
if any(reply == val for key,val in tups):
print(tups[0][0]) #key
else:
print('Not In Any Dictionary')
#output
1
Not In Any Dictionary