如何检查字典中的所有值是否都存在于列表中?

2024-05-29 10:07:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个用户偏好的字典,我想检查一下,看看是否所有的字典值都存在于一个列表中。你知道吗

例如,我有一本字典,如:

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

我有这样一个清单:

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

我正在检查字典中的所有值是否都存在于列表中。你知道吗

我该怎么做?你知道吗

编辑更具体:

我的字典是

userprefs = {'RON' : 'PHX'}

我的名单是

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

但是,如果我使用以下内容:

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

我得到一个空的匹配列表。你知道吗


Tags: 用户in列表for字典seqdctphx
3条回答

你可以试试下面的方法

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)

你可以试试这个:

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())

这样,您就可以在value变量中从字典中获取值,并检查它是否存在于列表中。你知道吗

方法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.

方法2:如Jon Clements所建议。更简洁明了的。你知道吗

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

相关问题 更多 >

    热门问题