简体   繁体   English

Python:如何迭代两个以上的词典?

[英]Python: How do I iterate over more than 2 dictionaries?

Not really sure what I'm doing wrong here. 不太确定我在这里做错了什么。 I thought the zip method would work to check if a value is in multiple lists? 我以为zip方法可以检查一个值是否在多个列表中? What I'd want it to do is check to see if that value is in any of those dictionaries, and if so, to print its key, but if not, then print only one string of ('Not in Any Dictionary'). 我希望它执行的操作是检查该值是否在那些词典中的任何一个中,如果是,则打印其键,但如果不是,则仅打印一个字符串(“不在任何词典中”)。 This method prints 40 of them for some reason with the real dictionaries. 此方法出于某些原因会用实际字典打印其中的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')

I think you can do it in a very simple way: 我认为您可以通过一种非常简单的方式做到这一点:

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')

The issue lies in how you've reused the variable names for key and value. 问题在于您如何将变量名重用于键和值。 Add a print statement to see the effect. 添加打印语句以查看效果。

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

The variables key and value get reassigned to the last entry in the tuple. 变量key和value重新分配给元组中的最后一个条目。

You can use the zip just fine if you handle unpacking later. 如果稍后再处理包装,则可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM