社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Ashish Bhatia

Ashish Bhatia 最近创建的主题
Ashish Bhatia 最近回复了
7 年前
回复了 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()