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

Illustrated Python | dictionary

編輯:Python
ShowMeAI research center

author : Han Xinzi @ShowMeAI

Tutorial address :http://www.showmeai.tech/tutorials/56

This paper addresses :http://www.showmeai.tech/article-detail/79

Statement : copyright , For reprint, please contact the platform and the author and indicate the source

1.Python Dictionaries (Dictionary)

Dictionary is another variable container model , And can store any type of object .

Each key value of the dictionary key=>value Yes, with a colon : Division , Comma between each key value pair , Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :

d = {key1 : value1, key2 : value2 }

Dictionaries (Dictionary)

Keys are usually the only , If you repeat the last key value pair, the previous one will be replaced , Value doesn't need to be unique .

>>> dict = {'a': 1, 'b': 2, 'b': '3'}
>>> dict['b']
'3'
>>> dict
{'a': 1, 'b': '3'}
# dict = {'name': 'runoob', 'likes': 123, 'url': 'www.runoob.com'}
dict = {'name': 'ShowMeAI', 'likes': 1000000, 'url': 'www.showmeai.tech'}
An example of a dictionary

The value can take any data type , but The key must be immutable , Such as a string , A number or tuple .

A simple dictionary example :

dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict2 = { 'abc': 123, 98.6: 37, (1,2):345 }
Dictionary partial operation a = {}

2. Visit the values in the dictionary

Put the corresponding key in the familiar square brackets , Here's a code example ( The code can be in On-line python3 Environmental Science Run in ):

dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Color']: ", dict['Color'])

The execution result of the above example :

dict['Name']: ShowMeAI
dict['Color']: Blue

If you access data with keys that are not in the dictionary , The output error is as follows :

dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'}
print("dict['Age']: ", dict['Age'])

The output of the above example :

Traceback (most recent call last):
File "<string>", line 5, in <module>
KeyError: 'Age'

3. Revise the dictionary

The way to add new content to the dictionary is to add new keys / It's worth it , Modify or delete existing keys / The value is shown in the following code example ( The code can be in On-line python3 Environmental Science Run in ):

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # to update
dict['School'] = "ShowMeAI" # add to
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

The output of the above example :

dict['Age']: 8
dict['School']: ShowMeAI

4. Delete dictionary elements

Can delete a single element can also empty the dictionary , Emptying takes only one operation .

Show delete a dictionary with del command , The following example :

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # Delete key is 'Name' The entry of
dict.clear() # Empty all dictionary entries
del dict # Delete Dictionary
print("dict['Age']: ", dict['Age'] )
print("dict['School']: ", dict['School'])

But this raises an exception , Because with del The post dictionary no longer exists :

Traceback (most recent call last):
File "<string>", line 9, in <module>
TypeError: 'type' object is not subscriptable

notes :del() Methods will also be discussed later .

(1) Dictionary key features

The dictionary value can take any python object , It can be a standard object , It can also be user-defined , But the key doesn't work .

Two important points to remember :

1) The same key is not allowed to appear twice . When creating, if the same key is assigned twice , The latter value updates the previous one , The following example :

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'ShowMeAI'}
print "dict['Name']: ", dict['Name']

The output of the above example :

dict['Name']: ShowMeAI

2) The key must be immutable , So you can use numbers , A string or tuple acts as , So using lists doesn't work , The following example :

dict = {['Name']: 'Zara', 'Age': 7}
print("dict['Name']: ", dict['Name'])

The output of the above example :

Traceback (most recent call last):
File "<string>", line 3, in <module>
TypeError: unhashable type: 'list'

5. Dictionary built-in functions and methods

Python The dictionary contains the following built-in functions :

Functions and descriptions

effect

cmp(dict1, dict2)

Compare two dictionary elements .

len(dict)

Count the number of dictionary elements , That's the total number of bonds .

str(dict)

The printable string representation of the output Dictionary .

type(variable)

Returns the type of variable entered , If the variable is a dictionary, return the dictionary type .

Python The dictionary contains the following built-in methods :

Functions and descriptions

effect

dict.clear()

Delete all elements in the dictionary

dict.copy()

Returns a shallow copy of a dictionary

dict.fromkeys(seq[, val])

Create a new dictionary , In sequence seq The middle element is the key of the dictionary ,val Is the initial value of all keys in the dictionary

dict.get(key, default=None)

Returns the value of the specified key , If the value is not returned in the dictionary default value

dict.has_key(key)

If the key is in the dictionary dict Back in true, Otherwise return to false

dict.items()

Return traversable ( key , value ) View object of tuple array

dict.keys()

Returns a view object of all keys in the dictionary

dict.setdefault(key, default=None)

and get() similar , But if the key does not exist in the dictionary , The key will be added and the value will be set to default

dict.update(dict2)

Put the dictionary dict2 Key / Value pair update to dict in

dict.values()

Returns the view object of all values in the dictionary

pop(key[,default])

Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given . otherwise , return default value .

popitem()

Returns and deletes the last pair of keys and values in the dictionary .

6. Video tutorial

Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition

https://www.bilibili.com/video/BV1yg411c7Nw

Data and code download

The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can visit foreign websites can also directly use google colab One click operation and interactive operation learning Oh !

This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :

  • Python Quick reference table

Expand references

  • Python course —Python3 file
  • Python course - Liao Xuefeng's official website

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