程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Adding and deleting dictionaries in Python

編輯:Python

For a dictionary :

book_dict = {
"price": 500, "bookName": "Python Design ", "weight": "250g"}

Add dictionary elements

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)

Delete dictionary elements

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 )

  1. 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 ;

  2. 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 ;

  3. 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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved