Py学习  »  Python

字典只捕获最后一个键值对Python

Sheikh Rahman • 5 年前 • 1432 次点击  

有一个名字字典和一个打印字典的函数。问题是当我运行create_user()函数时,它只捕获并打印最后的值。

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

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

我在下面也试过这个,前后抓拍。那没有解决。

def create_user():
  first_name=  input('Enter first name: ')
  users['first_name'] = first_name

  last_name= input('Enter last name: ')
  users['last_name']=last_name

  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={}
users['username'] = {}

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

           last_name= input('Enter last name: ')
           users['username']['last_name']=last_name

我仍然有同样的问题,没有得到所有的价值观
创建新用户?:是/否

输入名字:james

输入姓氏:jones

创建新用户?:是/否

输入名字:rob

输入姓氏:william

创建新用户?:是/否

出口 目录项

用户名{'名字':'罗伯','姓氏':'威廉'}

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51108
 
1432 次点击  
文章 [ 2 ]  |  最新文章 5 年前
user3757614
Reply   •   1 楼
user3757614    6 年前
users['last_name']=last_name 

你的问题是用户被用来存储单个用户的数据。你想要的是更像

users[username]['last_name']=last_name 

使用户成为字典的字典。用户名在哪里取决于你。如果你没有一个好的来源,让用户进入字典列表可能会更好。

Ashish Bhatia
Reply   •   2 楼
Ashish Bhatia    6 年前

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