# Python program to check if any key has all the given list elements

• Last Updated : 09 May, 2021

Given a dictionary with list values and a list, the task is to write a Python program to check if any key has all the list elements.

Examples:

Input : test_dict = {‘Gfg’ : [5, 3, 1, 6, 4], ‘is’ : [8, 2, 1, 6, 4], ‘best’ : [1, 2, 7, 3, 9], ‘for’ : [5, 2, 7, 8, 4, 1], ‘all’ : [8, 5, 3, 1, 2]}, find_list = [7, 9, 2]

Output : True

Explanation : best has all values, 7, 9, 2 hence 2 is returned.

Input : test_dict = {‘Gfg’ : [5, 3, 1, 6, 4], ‘is’ : [8, 2, 1, 6, 4], ‘best’ : [1, 2, 7, 3, 19], ‘for’ : [5, 2, 7, 8, 4, 1], ‘all’ : [8, 5, 3, 1, 2]}, find_list = [7, 9, 2]

Output : False

Explanation : No list has all values as find list.

Method #1 : Using issuperset() + loop

In this, we perform the task of finding the presence of all elements in the values list using issuperset(), and a loop is used to iterate all the keys.

## Python3

 # Python3 code to demonstrate working of# Extract values of Particular Key in# Nested Values Using list comprehension  # initializing dictionarytest_dict = {'Gfg': [5, 3, 1, 6, 4],              'is': [8, 2, 1, 6, 4],              'best': [1, 2, 7, 3, 9],             'for': [5, 2, 7, 8, 4, 1],              'all': [8, 5, 3, 1, 2]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing listfind_list = [7, 9, 2]  res = Falsefor key in test_dict:      # checking if all values present using     # superset    if set(test_dict[key]).issuperset(find_list):        res = True  # printing resultprint("Is any value list superset ? : " + str(res))

Output:

The original dictionary is : {‘Gfg’: [5, 3, 1, 6, 4], ‘is’: [8, 2, 1, 6, 4], ‘best’: [1, 2, 7, 3, 9], ‘for’: [5, 2, 7, 8, 4, 1], ‘all’: [8, 5, 3, 1, 2]}

Is any value list superset ? : True

Method #2 : Using any() + issuperset()

In this, we perform the task of checking for all keys using any(). Rest all functions are similar to the above method.

## Python3

 # Python3 code to demonstrate working of# Extract values of Particular Key in# Nested Values Using any() + issuperset()  # initializing dictionarytest_dict = {'Gfg': [5, 3, 1, 6, 4],             'is': [8, 2, 1, 6, 4],             'best': [1, 2, 7, 3, 9],             'for': [5, 2, 7, 8, 4, 1],             'all': [8, 5, 3, 1, 2]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing listfind_list = [7, 9, 2]  res = any(set(sub).issuperset(find_list)           for sub in test_dict.values())  # printing resultprint("Is any value list superset ? : " + str(res))

Output:

The original dictionary is : {‘Gfg’: [5, 3, 1, 6, 4], ‘is’: [8, 2, 1, 6, 4], ‘best’: [1, 2, 7, 3, 9], ‘for’: [5, 2, 7, 8, 4, 1], ‘all’: [8, 5, 3, 1, 2]}

Is any value list superset ? : True

My Personal Notes arrow_drop_up