在Python Dictionary中,元素的添加可以通过多种方式完成。通过定义值和键,例如Dict [Key] ='Value',可以将一次一个值添加到Dictionary中。可以使用内置update()方法更新Dictionary中的现有值。嵌套键值也可以添加到现有词典中。
注意 -添加值时,如果键值已存在,则值会更新,否则会将具有该值的新键添加到词典中。
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Add