私信  •  关注

Ashish Bhatia

Ashish Bhatia 最近创建的主题
Ashish Bhatia 最近回复了
6 年前
回复了 Ashish Bhatia 创建的主题 » 字典只捕获最后一个键值对Python

Dictionary是一个键值对。Dictionary有唯一的键。因此,当你运行程序时,选择第二次“Y”,它将更新现有的密钥“第一个名字”和“LaSTYNEX”。你 字典中不能有数据 就像{'firstúname':'A','last戋name':'B','first戋name':'C','last戋name':'D'}在这种情况下,键是重复的。但是,可以将名字保存为键,将姓氏保存为值。请参阅下面的代码。

users={}

def create_users():

    while True:
        choice=input('Create a new user?: Y/N ')
        if(choice=='y'):
           first_name=  input('Enter first name: ')
           # users['first_name'] = first_name

           last_name= input('Enter last name: ')
           # users['last_name']=last_name
           users[first_name] = last_name
           print(len(users))

        if(choice=='n'):
            print('Exit')
            break

def print_dir():
    print('Directory Item ','\n')
    for k,v in users.items():
        print(k,v)

create_users()
print_dir()