使用实际示例,编写一个 Python 程序来向字典添加键值对。
在此 程序中,我们使用 字典 update 函数向 字典 插入键值对。
key = input("Please enter the Key : ")
value = input("Please enter the Value : ")
myDict = {}
# Add Key-Value Pair to a Dictionary in Python
myDict.update({key:value})
print("\nUpdated Dictionary = ", myDict)

向字典插入键值对的程序 示例 2
此程序是向字典插入键值对的另一种方法。有关更多信息,请参阅 Python 页面。
key = input("Please enter the Key : ")
value = input("Please enter the Value : ")
myDict = {}
# Add Key-Value Pair to a Dictionary
myDict[key] = value
print("\nUpdated Dictionary = ", myDict)
向字典添加键值对的输出如下所示。
Please enter the Key : M
Please enter the Value : Mango
Updated Dictionary = {'M': 'Mango'}