Accessing items in lists within dictionary python

前端 未结 3 639
北恋
北恋 2021-02-04 10:47

I have a dictionary that has keys associated with lists.

mydict = {\'fruits\': [\'banana\', \'apple\', \'orange\'],
         \'vegetables\': [\'pepper\', \'carr         


        
相关标签:
3条回答
  • 2021-02-04 11:15

    You'll have to use a for, a simple if is not enough to check an unknown set of lists:

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

    An approach without an explicit for statement would be possible like this:

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

    which returns all keys which are associated with item. But internally, there's still some kind of iteration going on.

    0 讨论(0)
  • 2021-02-04 11:27
    mydict = {'fruits': ['banana', 'apple', 'orange'],
         'vegetables': ['pepper', 'carrot'], 
         'cheese': ['swiss', 'cheddar', 'brie']}
    
    item = "cheddar"
    if item in mydict['cheese']:
        print ("true")
    

    this works, but you have to reference the keys in the dictionary like cheese, vegetables etc instead because of the way you made the dictionary, hope this helps!

    0 讨论(0)
  • 2021-02-04 11:28
    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
    

    If you are going to do a lot of this kind of searching, I think you can create a reverse index for the original mydict to speed up querying:

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

    This way you don't have to traverse the values list every time to find an item.

    0 讨论(0)
提交回复
热议问题