【问题标题】:How to check if a key with an specific value in a dictionary exist on Python? Dictionary with arrays as values如何检查Python上是否存在字典中具有特定值的键?以数组为值的字典
【发布时间】:2022-01-25 18:13:04
【问题描述】:

我有以下字典,名为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,我试图在其他站点中寻找答案,但似乎包含数组的字典非常罕见,但最终是合法的,否则如何我可以评估上面的字典中是否确实存在一对特定的键值?

【问题讨论】:

  • 为什么不试试类似:'Amarillo.png' in the_dictionary_list['Color']

标签: arrays python-3.x dictionary if-statement notin


【解决方案1】:

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

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

输出:

错误

是的

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多