Home > Article > Backend Development > How to add value to dictionary in python
Dictionary is another mutable container model and can store any type of object.
Each key-value key=>value pair in the dictionary is separated by colon :. Each key-value pair is separated by comma,. The entire dictionary is included in curly braces {}. The format is as follows:
d = {key1 : value1, key2 : value2 }
The key is generally unique. If the last key-value pair is repeated, the previous one will be replaced. The value does not need to be unique.
>>>dict = {'a': 1, 'b': 2, 'b': '3'} >>> dict['b'] '3' >>> dict {'a': 1, 'b': '3'}
The value can be of any data type, but the key must be immutable, such as string, number or tuple.
A simple dictionary example:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary like this:
dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }
The way to add new content to the dictionary is to add new key/value pairs , modify or delete existing key/value pairs as follows:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # 更新 dict['School'] = "RUNOOB" # 添加 print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']
Output results of the above examples:
dict['Age']: 8 dict['School']: RUNOOB
For more Python related technical articles, please visit Python Tutorial column for learning!
The above is the detailed content of How to add value to dictionary in python. For more information, please follow other related articles on the PHP Chinese website!