更新1个在python字典中同时具有名字和姓氏的键

时间:2019-03-13 03:55:24

标签: dictionary key

我正在尝试创建联系人目录。在create_user()函数中,我通过格式化将名字和姓氏结合在一起,以便可以将其用作键并将电话号码分配为值。

问题:通过这种设计,我不能仅更新名字或姓氏。它更新整个键值。下面是一个示例:

Enter first name: jim
Enter last name: jones
Enter phone number: 9522013787
Create new user: Y/N ?n
FirstName: jim LastName: jones Phone: 952-201-3787
Enter name or phone number to search for: jones
Enter new name to update: Jamies
Jamies Phone: 952-201-3787  

我想要名字:jim姓氏:Jamies电话:952-201-3787
下面是代码。

#An empty directory to store contact information
user_dir={}

#A function to create new user
def create_user():
    while True:
        rsp=input('Create new user: Y/N ?')
        if rsp=='y':
                f_name = input('Enter first name: ')
                #First name cannot be empty
                while (len(f_name)==0):
                   print('First name cannot be empty')
                   f_name = input('Enter first name: ')
                l_name=input('Enter last name: ')
                #full_name is how we are combining names and use it as key in a dictionary
                full_name='FirstName: {} LastName: {}'.format(f_name,l_name)
                phone = input('Enter phone number: ')
                user_dir[full_name]=phone

        if rsp=='n':
            break

    return user_dir

#A function that takes a directory as arg and formats if phone number has 10 digits
#Will print user directory
def phone_formatter(aDir):
    for k,v in aDir.items():
        if(len(v)==10):
            area_code = v[0:3]
            mdl = v[3:6]
            lst = v[6:10]
            v=('{}-{}-{}'.format(area_code, mdl, lst))
            print(k, 'Phone:', v)
        else:
            print(k, 'Phone:', v)



#Update name or phone number (either key or value)
def update_user(aDir):
    search_term=input('Enter name or phone number to search for: ')
    for k,v in aDir.items():
        if search_term in k or search_term in v:
            new_name=input('Enter new name to update: ')
            user_dir[new_name]=user_dir.pop(k)
            break
        else:
            print('Did not find item')

create_user()
phone_formatter(user_dir)
update_user(user_dir)
phone_formatter(user_dir)

请提出是否有更简单的方法来实现该目标,如果没有,那么我应该如何设计我的create_user()函数。我可以做的1件事是:user_dir [f_name] = l_name。但是,如果您有更好的主意,请告诉我。预先感谢您的宝贵时间。

0 个答案:

没有答案