Skip to content Skip to sidebar Skip to footer

Check Key Exist In Python Dict

Below is the file output: apples:20 orange:100 Below is the code: d = {} with open('test1.txt') as f: for line in f: if ':' not in line: continue

Solution 1:

Use the in keyword.

if'apples'in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Post a Comment for "Check Key Exist In Python Dict"