Accessing items in lists within dictionary python

前端 未结 3 641
北恋
北恋 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.

提交回复
热议问题