For a dictionary :
book_dict = {
"price": 500, "bookName": "Python Design ", "weight": "250g"}
Method 1 :
Add the following information :
book_dict["owner"] = "tyson"
print(book_dict.keys())
Running results :
Method 2 :
You can also call update() Method to achieve the same effect , Parameter is a dictionary object
book_dict.update({
"owner": "tyson"})
Method 3 :
call update() Method , Parameters are keyword parameters
book_dict.update(owner="tyson")
print(book_dict.keys())
book_dict.update(weight="222")
print(book_dict["weight"])
explain : Also use dict Of update Method , But the keyword parameter is passed in ,key If it does not exist, it is to add elements (key Existence is modification value)
Be careful : Keyword parameter form ,key Objects can only be string objects
The result of the above code is as follows :
You can see the addition of owner, Revised weight
Method four :
Use update() Method , The parameter is the dictionary unpacking method
my_temp_dict = {
"name": " Councillor Wang ", "age": 18}
book_dict.update(**my_temp_dict)
print(book_dict.keys())
The effect is equivalent to :
book_dict.update(name=" Councillor Wang ", age=18)
Method 1 :del() Method
del(book_dict['price'])
print(book_dict.keys())
The operation results are as follows :
Method 2 :pop function
n = book_dict.pop('price')
print(n)
print(book_dict.keys())
The operation results are as follows :
Method 3 :clear function
book_dict.clear()
print(book_dict.keys())
The operation results are as follows :
python Medium dict( Dictionaries ):
Dictionary is another variable container model , Colon each key value pair ( : ) Division , Comma between each key value pair ( , ) Division , The whole dictionary consists of curly brackets {} Surround ;
The keys in a dictionary are usually unique , If it is repeated, the following key value pair will overwrite the previous one , However, dictionary values do not need to be unique ;
The value can take any data type , But the key must be immutable , Like strings , A number or tuple , But it can't be a list because the list is variable .