简体   繁体   English

如何在Python 3x中格式化字典键

[英]How to format dictionary keys in Python 3x

I am trying to format the dictionary key so that I can ask the user for the value and add that to the dictionary. 我正在尝试格式化字典键,以便可以要求用户输入值并将其添加到字典中。 so far my dictionary looks like this: 到目前为止,我的字典看起来像这样:

{'admin': ' '}

Expected output: 预期产量:

name: admin
admin's password: admin

Code: 码:

new dictionary = {'admin': 'admin'}

def example():
        name= input("name: ")
        #no value yet for the input key
        value = ""
        dict_users[name] = value
        check(dict_users)

def check(name):
    if name in dict_users.items():
        password = input('{name}'.format(**dict_users) + "s"+ " Password: "))
        #add password input to existing dictionary key
        dict_users[name] = password

#Dictionary of Users
dict_users = {}

No need to use string formatting here. 无需在此处使用字符串格式。

Also, see how you have to test if a key exists in a dict 另外,请查看如何测试字典中是否存在键

def check(name):
    if name in dict_users:
        password = input(name + "'s"+ " password: "))
        #add password input to existing dictionary key
        dict_users[name] = password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM