检查dict中是否存在包含给定项目的列表

时间:2017-02-08 10:54:51

标签: python

我有一个dict和这样的列表:

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 个答案:

答案 0 :(得分:2)

temp in hey.values()怎么样?

答案 1 :(得分:0)

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

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']