首页 > 解决方案 > 如何在 Python 中自动将新值添加到字典中

问题描述

我正在尝试编写一种算法,当用户键入新内容时,它可以“自动”向字典添加值。例如...

my_friends = {}

friends = input("What is your friend name?")

#when i type the name, programm should add it itself. Thanks for advices.

标签: pythonalgorithmdictionary

解决方案


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使用字典的内置方法更新字典updateupdate接受另一个字典并使用它来修改当前字典的内容friends

因此,假设您Jessica在输入中键入,它将friends{"Jessica": None}. dict[key]稍后您可以通过在字典上执行符号来访问此添加的键、值对。所以friends["Jessica"]将等于None因为在函数中我们只是将输入字符串添加为键,并None作为该键的默认值。

希望有帮助。


推荐阅读