gpt4 book ai didi

python - 功能不是向我的字典添加信息

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:20 24 4
gpt4 key购买 nike

所以我的函数是这样创建的:

def create_contact(contacts, first, last, email, age, phone):
"""
Creates a contact.
"""

contacts[(first, last)] = [email, age, phone]


def contains_contact(contacts, first, last):
"""
Checks to see if the dictionary contains a contact.
"""
if (first.lower(), last.lower()) in contacts == True:
return(True)
else:
return(False)

然后在我的代码底部我有我的主要功能,如下所示:

def main():
# The Dictionary
contacts = {}
# Provided Test Code
create_contact(contacts, "Katie", "Katz", "katie.katz@gmail.com",
25, "857-294-2758")
#Checks to see if item in dictionary exists
print("Creation of Katie Katz: {}".format(
"Passed" if contains_contact(contacts, "Katie", "kaTz") else
"Failed"))

我不知道我哪里错了。这些项目似乎没有添加到我的字典中。不确定为什么,也许我的尝试都是错误的。

最佳答案

向字典中添加项目工作正常,但您忘记在 create_contact 中将名字和姓氏转换为小写。但是,您确实在 contains_contact 中执行了此操作,这就是您的代码不起作用的原因。

def create_contact(contacts, first, last, email, age, phone):
"""
Creates a contact.
"""

contacts[(first.lower(), last.lower())] = [email, age, phone]

此外,您的 contains_contact 函数可以简化:

def contains_contact(contacts, first, last):
"""
Checks to see if the dictionary contains a contact.
"""
return (first.lower(), last.lower()) in contacts

关于python - 功能不是向我的字典添加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46660016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com