拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何检查Python上是否存在字典中具有特定值的键?以阵列为值的字典

如何检查Python上是否存在字典中具有特定值的键?以阵列为值的字典

白鹭 - 2022-02-22 1964 0 0

我有以下字典称为the_dictionary_list

the_dictionary_list= {'Color': ['Amarillo.png', 'Blanco.png',
'Rojirosado.png', 'Turquesa.png', 'Verde_oscuro.png', 'Zapote.png'],
'Cuerpo': ['Cuerpo_cangrejo.png'], 'Fondo': ['Oceano.png'], 'Ojos':
['Antenas.png', 'Pico.png', 'Verticales.png'], 'Pinzas':
['Pinzitas.png', 'Pinzotas.png', 'Pinzota_pinzita.png'], 'Puas':
['Arena.png', 'Marron.png', 'Purpura.png', 'Verde.png']}

我想检查它是否有一个带有特定值的特定键(在它的阵列中),所以我输入了以下代码:

if ('Color', 'None') in the_dictionary_list.items():
    print('This is True')
else:
    print('This is False')
    
if ('Color', 'Amarillo.png') in the_dictionary_list.items():
    print('This is True')
else:
    print('This is False')

输出如下:

这是 50% 错误,因为第二个if statement应该打印This is True,我试图在其他网站上寻找答案,但似乎带有阵列的字典非常不常见,但最终是合法的,我还能如何评估特定的一对键-value 确实存在于上面的字典中?

uj5u.com热心网友回复:

我想通了,只需使用一个函式:

the_dictionary_list= {
    'Color': ['Amarillo.png', 'Blanco.png', 'Rojirosado.png', 'Turquesa.png', 'Verde_oscuro.png', 'Zapote.png'],
    'Cuerpo': ['Cuerpo_cangrejo.png'],
    'Fondo': ['Oceano.png'],
    'Ojos': ['Antenas.png', 'Pico.png', 'Verticales.png'],
    'Pinzas': ['Pinzitas.png', 'Pinzotas.png', 'Pinzota_pinzita.png'],
    'Puas': ['Arena.png', 'Marron.png', 'Purpura.png', 'Verde.png']}

def existe(llave, valor, dicc):
    return llave in dicc and valor in dicc[llave]

print(existe('Color', 'None', the_dictionary_list))
print(existe('Color', 'Amarillo.png', the_dictionary_list))

输出:

错误的

真的

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *