嵌套字典键,值对未正确打印-Python

时间:2019-02-11 05:27:50

标签: dictionary nested

当我阅读Eric M的Python速成课程时,在第9章中它在Dictionary部分引入了任意关键字参数。我决定根据到目前为止所获得的知识来编写通讯录。这是代码。

import random

print('Enter choice 1-6:'),'\n'
print('', '1-Create new profile','\n',
      '2-Update existing profile','\n',
      '3-Delete a profile','\n',
      '4-View Directory','\n',
      '5-Search Directory','\n',
      '6-Exit Profile program')

#Global Variables
user_names={} # used in name_dictionary() to store names only
user_ids=[] # used to contain randomly generated user ids
user_directory={} # will combine userid and names in a new dictionary

#name_dictionary is a dictionary that saves names as ('last_name', 'jones', 'first_name', 'jim')
def name_dictionary(**options):
    fn=input('Enter first name: ')
    user_names['first_name']=fn
    ln = input('Enter last name: ')
    user_names['last_name'] = ln

    for key,value in user_names.items():
        user_names[key]=value

    choice=input('You can add additional items such as phone, email-Add/No')
    if (choice=='y'):
        em = input('Enter email address: ')
        options['email'] = em
        phn = input('Enter phone: ')
        options['phone'] = phn

        for key, value in options.items():
            options[key] = value

        for key,value in user_names.items():
            for k, v in options.items():
                print()
        return(key,value,k,v)

    else:
        print('Extra information not added')
        for k, v in user_names.items():
            return (k, v)

# generate_id is a list that randomly generates userids andsaves in a list example user_id69
def generate_id():
    # as of now I am not focusing on generating unique random or checking for dup id
    user_id = 'user_id' + str(random.randint(0, 100))
    user_ids.append(user_id)

    return user_id


# addUserIDToDict is a dictionary adds the names and ids to a dictionary which should look like
# user_id69 ('last_name', 'jones', 'first_name', 'jjim')
def addUserUserIDToDict():
    user_directory[generate_id()] = name_dictionary()
    while True:
        # user_directory[generate_id()] = name_dictionary()
        print('Add another entry?(stop to quit)')
        choice = input()
        if (choice == 'y' and choice != 'stop'):
            user_directory[generate_id()] = name_dictionary()

        else:
            break

    return user_directory


# search_user function, lets user search by Id or Name
def search_user():
    search_option = input('Search by name or id?:..')

    if (search_option == 'name'):
        search_name = input('Enter name')
        for k, v in user_directory.items():
            for key, value in user_names.items():
                if (search_name == value):
                    print()
        print(search_name, ' found in directory')
        print('That name is in position', key)


    else:
        print('That name not found')

    if (search_option == 'id'):
        search_id = input('What is the id: ?')
        if search_id in user_directory.keys():
            print(search_id, ' found in directory')
            print(user_directory.get(search_id))

        else:
            print(search_id, ' not found in directory')


# Prints value of items in user directory
def print_directory():
    print('==View Current Directory==')
    if (len(user_directory) == 0):
        print('No entry to show')
    else:
        for k, v in user_directory.items():
            print(k, v)


# Used for finding a name by last or first name and then modify/change the name
def modify_profile():
    print("You can modify names or an entry to add additional items")

    modify_name = input('Enter name to modify')

    for k, v in user_directory.items():
        for key, value in user_names.items():
            if(modify_name==value):
                print(modify_name, ' found in directory')
                print('That name is in position', key)
                update_name = input('Enter what is the change to make')
                user_names[k] = update_name # updates the name in user_names dictionary
                user_directory[k] = update_name # updates in user_dictionary 
            break

        else:
            print('That name not found')


# Finds a contact and then removes it. I will use pop so that I can later track it.
def delete_user():
    search_name = input('Enter name')

    if (search_name in user_names.values()):
        print("Name found")
        to_remove = input('Do you want to proceed to delete that contact? Y/N..?')
        if (to_remove == 'Y'):
            for k, v in user_directory.items():
                for key, value in user_names.items():
                    print()
            print("Removing id", k)
            del user_directory[k]

    else:
        print('That contact does not exist')


# Menu items
while True:
    print('Pick an option from menu above')
    print('Options are 1-6, invalid selection will exit program')
    user_choice = int(input())  # used for user input for menu
    if (user_choice == 1):
        addUserUserIDToDict()
        print_directory()

    elif (user_choice == 2):
        modify_profile()

    elif (user_choice == 3):
        delete_user()

    elif (user_choice == 4):
        print_directory()

    elif (user_choice == 5):
        search_user()

    elif (user_choice == 6):
        print('Exit Program')
        break

    elif (user_choice < 1 or user_choice > 6):
        print('Wrong selection.Menu between 1 to 6')
        print('Exit Program')
        break

我的第一个问题是我无法从user_names打印整个键值。我在那里使用return语句。如果我将其更改为print(k,v),则可以正常工作。但是,如果不使用return,则无法在addToDict函数中使用它。另一个问题是我不确定为什么会这样,当我尝试更新名字或姓氏时,它也会更新其他条目。

这是运行时出现的问题

问题1 :打印来自def name_dictionary(** options)函数的部分数据

user_id74('first_name','sam')**不打印姓氏

user_id15(“姓氏”,“琼斯”,“电话”,“ 952”)***不打印名字和电子邮件地址

问题2 :从def Modify_profile()更新功能来更新其他条目

更改前:

user_id85('last_name','rahman')

user_id24(“姓氏”,“琼斯”)

更改后:

user_id85 1月***请注意,上面的姓氏部分消失了。

user_id24(“姓氏”,“琼斯”)

我知道外观不好,还有很多改进的余地,这肯定会花费您宝贵的时间。但是,如果您可以提供一些帮助的提示/方向。谢谢

0 个答案:

没有答案
相关问题