-3

So I have a dictionary of user preferences that I'd like to check and see if ALL of the dictionary values exist in a list.

For example, I have a dictionary like:

dct = { 'key1' : 'value1', 'key2' : 'value2'}

And I have a list like so:

lst = ['list1', 'list2', 'list3', 'list4']

I'm trying to check if all of the values in the dictionary exist in the list.

How do I do this?

EDIT to be more specific:

My dictionary is

userprefs = {'RON' : 'PHX'}

My list is

poss_matches = [['misc0', 'misc1', 'misc2', 'misc3', 'misc4', 'misc5', 'misc6', 'misc7', 'PHX-']]

However, if I use something like:

    for seq in poss_matches:
        for p in userprefs:
            if userprefs[p] in seq:
                matches.append(seq)

I get an empty list for matches.

4 Answers4

1

You could try this :

def checker():
    for value in dct.values():
        if value in lst:
            continue
        else:
            return False
    return True

dct = { 'key1' : 'list1', 'key2' : 'list1'}
lst = ['list1', 'list2', 'list3', 'list4']
print(checker())

By this you will be fetching values from dictionary in value variable and checking whether it's present in list.

anurag0510
  • 763
  • 1
  • 8
  • 17
1

Method 1:

myDict = { 'key1' : 'value1', 'key2' : 'value2'}
values_myDict = myDict.values() # Outputs all the values of a dictionary in a list.
values_myDict
    ['value1', 'value2']

# Use set() - In case myList has all the values of the dictionary, we will get True, else False
myList = ['list1', 'list2', 'list3', 'list4', 'value1', 'value2']
bool_value = set(values_myDict) < set(myList)
bool_value
    True     # because both 'value1' & 'value2' are presnt.

myList = ['list1', 'list2', 'list3', 'list4', 'value1',]
bool_value = set(values_myDict) < set(myList)
bool_value
    False    # because 'value2' is not present.

Method 2: As suggested by Jon Clements. A more concise and succinct one.

myDict = { 'key1' : 'value1', 'key2' : 'value2'}
myList = ['list1', 'list2', 'list3', 'list4', 'value1', 'value2']
bool_value = set(myDict.values()).issubset(myList)
bool_value
    True

myList = ['list1', 'list2', 'list3', 'list4', 'value1']
bool_value = set(myDict.values()).issubset(myList)
bool_value 
    False
cph_sto
  • 7,189
  • 12
  • 42
  • 78
1

You need all() with for loop

dct = { 'key1' : 'list1', 'key2' : 'list2','k3':'list3','k4':'list4'}
lst = ['list1', 'list2', 'list3', 'list4']

all(x in lst for x in dct.values())

Output:

True
Sociopath
  • 13,068
  • 19
  • 47
  • 75
  • I'm trying to check if all of the values in the dictionary exist in the list - `all(x in lst for x in dct.values())` – cph_sto Jan 04 '19 at 12:31
1

You can try below approach

dct = { 'key1' : 'list1', 'key2' : 'list3'}
lst = ['list1', 'list2', 'list3', 'list4']
flag='N'
for each in dct:
   if dct[each] in lst:
      flag='Y'
   else:
      flag='N'
print (flag)
Akshay Sapra
  • 436
  • 5
  • 22