Python 打印出字典中与多个值关联的键

Python 打印出字典中与多个值关联的键,python,dictionary,Python,Dictionary,如果在调用函数时提出了一个值项,我将尝试打印出字典中与该值项关联的键 例如(这是可行的): 然而,每当我向一个键添加多个值时,它就会停止工作,我不知道为什么 dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : 'der Katze' , 'Bird': 'der Vogel'} 不给我输出,它不打印x 有人能帮忙吗?您的上述情况: ... for x, y in items: if y == pet: ... 测试值(键、值对)是否为值

如果在调用函数时提出了一个值项,我将尝试打印出字典中与该值项关联的键

例如(这是可行的):

然而,每当我向一个键添加多个值时,它就会停止工作,我不知道为什么

dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : 'der Katze' , 'Bird': 'der Vogel'}
不给我输出,它不打印x

有人能帮忙吗?

您的上述情况:

...
for x, y in items:
    if y == pet:
...
测试值(键、值对)是否为值
pet
。但是,当字典值是一个列表时,您确实想知道
pet
是否在列表中。所以你可以试试:

...
for x, y in dic.items():
    if pet in y:
        print x
请注意,这两种情况都返回True:

pet = "crocodile"
list_value = ["I", "am", "a", "crocodile"]
single_value = "crocodile"

pet in list_value
--> True

pet in single_value
--> True
希望这能帮助您改善上述状况:

...
for x, y in items:
    if y == pet:
...
测试值(键、值对)是否为值
pet
。但是,当字典值是一个列表时,您确实想知道
pet
是否在列表中。所以你可以试试:

...
for x, y in dic.items():
    if pet in y:
        print x
请注意,这两种情况都返回True:

pet = "crocodile"
list_value = ["I", "am", "a", "crocodile"]
single_value = "crocodile"

pet in list_value
--> True

pet in single_value
--> True

希望这对你有所帮助,因为你把字符串和列表混在一起了,为什么不把它们都列出来呢

def test(pet): 
  items = dic.items()
  key = dic.keys()
  values = dic.values()
  for x, y in items:
      for item in y: # for each item in the list of dogs
          if item == pet:
              print x

dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : ['der Katze'] , 'Bird': ['der Vogel']}
test('der Hund')


因为在您的情况下,顺序似乎并不重要,而且您只是在检查成员资格,所以最好使用
集合
。您也可以简单地检查
是否在y
中,而不是自己进行迭代

def test(pet):
  for k, v in dic.items():
      if pet in v:
          print k

dic = {'Dog': {'der Hund', 'der Katze'}, # sets instead of lists
       'Cat': {'der Katze'},
       'Bird': {'der Vogel'}}

test('der Hund')


它不起作用,因为你混合了字符串和列表,为什么不把它们全部列出来呢

def test(pet): 
  items = dic.items()
  key = dic.keys()
  values = dic.values()
  for x, y in items:
      for item in y: # for each item in the list of dogs
          if item == pet:
              print x

dic = {'Dog': ['der Hund', 'der Katze'] , 'Cat' : ['der Katze'] , 'Bird': ['der Vogel']}
test('der Hund')


因为在您的情况下,顺序似乎并不重要,而且您只是在检查成员资格,所以最好使用
集合
。您也可以简单地检查
是否在y
中,而不是自己进行迭代

def test(pet):
  for k, v in dic.items():
      if pet in v:
          print k

dic = {'Dog': {'der Hund', 'der Katze'}, # sets instead of lists
       'Cat': {'der Katze'},
       'Bird': {'der Vogel'}}

test('der Hund')


你确定你的字典是正确的吗?你确定你的字典是正确的吗?那当然是,谢谢你的快速回复和易懂的解释!!!!!非常感谢您的快速回复和易于理解的解释!!!!!什么意思?对于列表中的项目?@user2352648这只是一条注释,表明我正在浏览列表中的每个项目?对于列表中的项目,你是什么意思?@user2352648这只是一条注释,表明我正在浏览列表中的每个项目