Friday, 7 May 2021

how to check if a given value exists in the dictionary key list

 

 

mydict = {'is': [1, 3, 4, 8, 10], #these are the dictionary key list in the [] third bracket
             'at': [3, 10, 15, 7, 9],
             'test': [5, 3, 7, 8, 1],
             'this': [2, 3, 5, 6, 11],
             'why': [10, 3, 9, 8, 12]}
# Check if a value exist in dictionary with multiple key
v = 3
# Get list of keys that contains the given value
k=[key
        for key, k in mydict.items()
        if v in k]

if k:
    print(k)
else:
    print('Value does not exist in the dictionary')

No comments:

Post a Comment