Reputation: 15
I'm writing a code to check if the key given exists in the dictionary or not, the code goes like this:
x=str()
def check_key(d,x):
for i in d:
if i==x:
print("exists")
else:
print("not exist")
check_key({'etisalat':'011','vodafone':'010'},"etisalat")
the problem is, if it exists, the code prints exists and not exist, and if it doesn't exist it prints not exist twice, what do I need to edit?
tried changing indentation of the print statements, tried putting them into variables and returning the value but it doesn't return
x=str()
def check_key(d,x):
for i in d:
if i==x:
print("exists")
else:
print("not exist")
check_key({'etisalat':'011','vodafone':'010'},"etisalat")
the output is (exists,not exist) if it exists, and (not exist,not exist) if it doesn't exist, it's supposed to print one output
Upvotes: 0
Views: 46
Reputation: 49814
Since the dict has two keys, you are looping and testing twice and thus getting two prints. Try:
def check_key(d,x):
for i in d:
if i==x:
print("exists")
return
print("not exist")
check_key({'etisalat':'011','vodafone':'010'},"etisalat")
You can also test directly instead of looping:
def check_key(d,x):
if x in d:
print("exists")
else:
print("not exist")
check_key({'etisalat':'011','vodafone':'010'},"etisalat")
Upvotes: 1
Reputation: 8131
With for i in d
you are looping over every item in the dictionary. Thus you will do something for both keys in the dictionary.
You do not need to write this function, it already exists. It's the in
method of a dictionary.
d = {'etisalat':'011','vodafone':'010'}
print('etisalat' in d)
>>> True
Upvotes: 0