Python 检查dict中是否存在包含给定项目的列表
我有一份口述和这样的清单:Python 检查dict中是否存在包含给定项目的列表,python,Python,我有一份口述和这样的清单: hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']} temp = ['Cook', 'a'] 我想检查hey中是否存在temp。我的代码: def checkArrayItem(source,target): global flag flag = True for item in source: if (item in target): conti
hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']}
temp = ['Cook', 'a']
我想检查hey
中是否存在temp
。我的代码:
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
进行此检查的更优雅的方法是什么?如何使用
设置与容器进行比较:
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']
只需使用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']
你的意思是你有一个dict
和一个列表
。谢谢,我看到了链接。你的意思是你有一个dict
和一个列表
。谢谢,我看到了链接。谢谢,excelleteans@RelaxZeroC:不客气。谢谢你,卓越ans@RelaxZeroC:不用客气。谢谢,很好用。谢谢,很好用。