python - 如何在 Python 中自动将新值添加到字典中
问题描述
我正在尝试编写一种算法,当用户键入新内容时,它可以“自动”向字典添加值。例如...
my_friends = {}
friends = input("What is your friend name?")
#when i type the name, programm should add it itself. Thanks for advices.
解决方案
friends = {}
def addFriend():
friends.update({input("What is your friend name?"): None})
addFriend() # asks for the friend...
addFriend() # asks for another friend...
print(friends)
这是一个使用函数的示例,在我们的例子中,它被命名为addFriend
. 该函数基本上只是friends
使用字典的内置方法更新字典update
。update
接受另一个字典并使用它来修改当前字典的内容friends
。
因此,假设您Jessica
在输入中键入,它将friends
以{"Jessica": None}
. dict[key]
稍后您可以通过在字典上执行符号来访问此添加的键、值对。所以friends["Jessica"]
将等于None
因为在函数中我们只是将输入字符串添加为键,并None
作为该键的默认值。
希望有帮助。
推荐阅读
- node-red - 如何禁用从 Node-RED 到 syslog 的日志记录
- reactjs - 'TableInstance{}' 类型上不存在 react-table 分页属性
- python - 使用带有矢量化的 numpy.einsum 的 Numpy martix 乘法
- wordpress - WP Elementor 选择控制前缀类前缀 %s 字符串格式
- javascript - 为什么 displayName 没有得到更新?使用 onAuthChanged
- speech-to-text - 如何在没有先前语音注册的情况下使用 Microsoft 语音到文本进行说话人识别(分类)?
- javascript - 如果输入字段和文件为空,如何禁用按钮?
- javascript - 从 JSON 文件导入数据到 JS
- azure - 如何一次从多个订阅中读取数据
- npm - 如何自动更新 npm?