2017-02-08 43 views
0

我有一个字典和像这样的列表:检查清单,给定的项目出现在字典

hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']} 
temp = ['Cook', 'a'] 

我要检查,如果temp存在于hey。我的代码:

def checkArrayItem(source,target): 
    global flag 
    flag = True 

    for item in source: 
     if (item in target): 
      continue 
     else: 
      flag = False 
      break 
for i,arr in enumerate(hey) : 
    if (len(temp) == len(hey[arr])): 
     checkArrayItem(temp,hey[arr]) 
     if (flag): 
      print('I got it') 
      break 

什么是更优雅的方式来做这个检查?

+2

你的意思是你有一个'dict'和'list'。 – khelwood

+0

谢谢,我已经看到链接。 –

回答

2

temp in hey.values()怎么样?

+0

谢谢,excellete ans –

+0

@RelaxZeroC:不客气。 –

0

只需使用set s到完全比较容器:

In [40]: hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']} 

In [41]: temp = {'Cook', 'a'} 
# This will give you the keys within your dictionary that their values are equal to tamp 
In [42]: [k for k, v in hey.items() if set(v) == temp] 
Out[42]: ['1'] 
+0

谢谢,它很好用。 –