为什么即使条件不同,代码也会打印两个答案

时间:2019-06-16 15:28:44

标签: python

我正在编写代码以检查给定的密钥是否存在于字典中,代码如下所示:

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")

如果存在,则输出为(存在,不存在),如果不存在,则为(不存在,不存在),应该打印一个输出

2 个答案:

答案 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