我正在编写代码以检查给定的密钥是否存在于字典中,代码如下所示:
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")
问题是,如果存在,则打印的代码存在并且不存在;如果不存在,则打印的代码不存在两次,我需要编辑什么?
尝试更改打印语句的缩进,尝试将它们放入变量中并返回值,但不会返回
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")
如果存在,则输出为(存在,不存在),如果不存在,则为(不存在,不存在),应该打印一个输出
答案 0 :(得分:1)
由于dict有两个键,因此您要循环测试两次,从而得到两次打印。试试:
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")
您也可以直接测试而不是循环进行测试:
def check_key(d,x):
if x in d:
print("exists")
else:
print("not exist")
check_key({'etisalat':'011','vodafone':'010'},"etisalat")
答案 1 :(得分:0)
使用for i in d
,您可以遍历字典中的每个项目。因此,您将对字典中的两个键都进行操作。
您不需要编写此函数,因为它已经存在。这是字典的in
方法。
d = {'etisalat':'011','vodafone':'010'}
print('etisalat' in d)
>>> True