【问题标题】:Accessing items in lists within dictionary python访问字典python中列表中的项目
【发布时间】:2012-06-15 19:07:25
【问题描述】:

我有一个字典,其中包含与列表关联的键。

mydict = {'fruits': ['banana', 'apple', 'orange'],
         'vegetables': ['pepper', 'carrot'], 
         'cheese': ['swiss', 'cheddar', 'brie']}

我想要做的是使用 if 语句,如果我在字典中的任何列表中搜索 item 及其它将返回键。这就是我正在尝试的:

item = cheddar
if item in mydict.values():
    print key 

但它什么也没做,输出应该是:

cheese

这似乎是一件简单的事情,但我就是想不通。任何帮助都很棒。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    您必须使用for,一个简单的if 不足以检查一组未知列表:

    for key in mydict.keys():
        if item in mydict[key]:
            print key
    

    没有明确的for 语句的方法可能是这样的:

    foundItems = (key for key, vals in mydict.items() if item in vals)
    

    返回与item 关联的所有键。但在内部,仍在进行某种迭代。

    【讨论】:

    • 如果我想“访问”与每个键关联的列表,并将其转换为 for 循环内的 temp_array 以供我自己计算,该怎么办?假设我必须检查有关列表值的一些内容。在我的例子中,列表将只包含整数。
    • @FrancescoCastellani 取决于您的实际用例;你可以在任何迭代中访问mydict[key],就像在第一个sn-p中一样;或者你可以做类似map(mydict.values(), own_calculations)的事情。
    【解决方案2】:
    mydict = {'fruits': ['banana', 'apple', 'orange'],
         'vegetables': ['pepper', 'carrot'], 
         'cheese': ['swiss', 'cheddar', 'brie']}
    
    item = "cheddar"
    if item in mydict['cheese']:
        print ("true")
    

    这可行,但是由于您制作字典的方式,您必须引用字典中的键,例如奶酪、蔬菜等,希望这会有所帮助!

    【讨论】:

      【解决方案3】:
      mydict = {'fruits': ['banana', 'apple', 'orange'],
           'vegetables': ['pepper', 'carrot'], 
           'cheese': ['swiss', 'cheddar', 'brie']}
      
      item = "cheddar"
      
      for key, values in mydict.iteritems():
          if item in values:
              print key
      

      如果你打算做很多这样的搜索,我认为你可以为原来的mydict创建一个反向索引来加快查询速度:

      reverse_index = {}
      
      for k, values in mydict.iteritems():
           for v in values:
               reverse_index[v] = k
      
      print reverse_index.get("cheddar")
      print reverse_index.get("banana")
      

      这样您就不必每次都遍历values 列表来查找项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        • 1970-01-01
        • 2021-07-11
        • 1970-01-01
        相关资源
        最近更新 更多