Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check key exist in python dict

Tags:

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         key, value = line.strip().split(":", 1)         d[key] = value  for k, v in d.iteritems():     if k == 'apples':          v = v.strip()          if v == 20:              print "Apples are equal to 20"          else:              print "Apples may have greater than or less than 20"        if k == 'orrange':          v = v.strip()          if v == 20:             print "orange are equal to 100"          else:             print "orange may have greater than or less than 100" 

In above code i am written "if k == 'orrange':", but its actually "orange" as per output file.

In this case I have to print orrange key is not exist in output file. Please help me. How to do this

like image 254
pioltking Avatar asked May 17 '17 21:05

pioltking


People also ask

How do you check if a key exists in a dictionary Python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.

How do you check if a key-value exists in a dictionary?

Check if a key-value pair exists in a dictionary: in operator, items() To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

Which operator tests to see if a key exists in a dictionary?

The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers.


1 Answers

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.') 
like image 153
Pedro von Hertwig Batista Avatar answered Dec 05 '22 19:12

Pedro von Hertwig Batista