简体   繁体   English

"访问字典python中列表中的项目"

[英]Accessing items in lists within dictionary python

I have a dictionary that has keys associated with lists.我有一个字典,其中包含与列表关联的键。

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

You'll have to use a for , a simple if is not enough to check an unknown set of lists: 你必须使用for ,一个简单的if不足以检查一组未知的列表:

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

An approach without an explicit for statement would be possible like this: 没有明确的for语句的方法可能是这样的:

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

which returns all keys which are associated with item . 返回与item关联的所有键。 But internally, there's still some kind of iteration going on. 但在内部,仍然存在某种迭代。

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! 这是有效的,但你必须引用字典中的键,如奶酪,蔬菜等,因为你制作字典的方式,希望这有帮助!

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: 如果您要进行大量此类搜索,我认为您可以为原始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")

This way you don't have to traverse the values list every time to find an item. 这样,每次查找项目时都不必遍历values列表。

input<\/strong>输入<\/strong>

a = ["AB", "corona"]
b = ["india",'openVINO']
c = ["korea"]
d = ["26", "10.mp3", "Nvidia.mp4"]
e = ["washington DC",6]
f = ['swiss']

import itertools

lst = [a,b,c,d,e,f]
# print(lst)
lsts = list(itertools.product(*lst))
for lst in lsts:
  print('\n')
  for con in lst:
    print(con)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM