【问题标题】:Printing out the key associated with multiple values in a dictionary [duplicate]打印出与字典中多个值关联的键[重复]
【发布时间】:2013-05-17 01:36:44
【问题描述】:

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

例如(这有效):

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

  items = dic.items()
  key = dic.keys()
  values = dic.values()
  for x, y in items:
    if y == pet:
      print x

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

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

不给我输出它不打印 x。

有人可以帮忙吗?

【问题讨论】:

  • 你确定你的字典是正确的吗?

标签: python dictionary


【解决方案1】:

您的上述情况:

...
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

希望对你有帮助

【讨论】:

  • 肯定做到了,感谢您的快速回复和易于理解的解释!!!!!
【解决方案2】:

这不起作用,因为您将字符串和列表混合在一起,为什么不将它们全部设为列表?

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

>>> 
Dog

由于订单在您的情况下似乎并不重要,而且您只是在检查会员资格,因此最好使用set。您也可以简单地检查if pet in 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')

>>> 
Dog

【讨论】:

  • 你是什么意思#for item in list?
  • @user2352648 这只是一条评论,表明我正在浏览列表中的每个项目
猜你喜欢
  • 2019-06-20
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
相关资源
最近更新 更多