Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 == 'orange':", but its actually "orange" as per output file.

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

1 Answer

0 votes
by (106k points)

To check whether a key exists in python dict you can use the in keyword. See the code below:-

if 'apples' in d: 

if d['apples'] == 20: 

print('20 apples') 

else: 

print('Not 20 apples')

Related questions

0 votes
1 answer
+3 votes
2 answers
0 votes
1 answer
+1 vote
1 answer
asked Jul 5, 2019 in Python by selena (1.6k points)

Browse Categories

...