Handbook of python3.5 cultivation 10

Source: Internet
Author: User

Dictionary


Use of dictionaries

The dictionary has been constructed in Python, allowing us to easily find a particular key (similar to a phonetic or stroke index), so that the corresponding value can be found by the key (similar to a specific word).


Creating and using dictionaries

The dictionary is created in the following format

A={key1:value1,key2:value2}

Creation of an empty dictionary

b={}

Note: The key must be unique when creating the dictionary, but the value does not have to be. The value can take any data type, and the key must be immutable, such as a string, a number, or a tuple.


dict function

The Dict function can build a dictionary through other mappings (such as other dictionaries) or key/value sequence pairs.

For example:

student=[(' name ', ' Du Yuheng '), (' Number ', ' 666 '),]detai=dict (' Number ', ' ", ' Student ') print (' Student details: ', ' Detai ') print (' Student name: ', detai[' name ']) Print (' Student No.: ', detai[' number ')

C:\python\python.exe c:/python.py/zidian.py

Student Details: {' name ': ' Du Yuheng ', ' number ': ' 666 '}

Student Name: Du Yuheng

Student Number: 666

In the example above, you can see that the dict function converts the love sequence into a dictionary.

The Dict function can also create a dictionary from a keyword.

For example:

Detail = Dict (name= ' Du Yuheng ', number= ' 666 ') print (' Student details: ', detail)

C:\python\python.exe c:/python.py/zidian.py

Student Details: {' name ': ' Du Yuheng ', ' number ': ' 666 '}

Creating a dictionary with keywords is a very useful feature of the dict function.


Basic operation of the dictionary

The basic operation of a dictionary is similar to a sequence (sequence) in many ways, and supports the deletion of modifications.


Modify Dictionary

New content is added to the dictionary by adding new key/value pairs, modifying or deleting existing key/value pairs, and modifying or deleting existing keys/values.

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 '} #更新徐伟的学号student [' Xu Wei ']= ' 999 ' Print (' Xu Wei ' number is:% (Xu Wei) s '%student) # Add a new student student[' Du Chaoli ']= ' "Print (' Du Chaoli ' number is:% (Du Chaoli) s '%student) print (' All student info: ', student)

C:\python\python.exe c:/python.py/zidian.py

Xu Wei's number is: 999

Du Chaoli's number is: 1000

Information for all students: {' Du Chaoli ': ' 1000 ', ' Xu Wei ': ' 999 ', ' Du Yuheng ': ' 666 ', ' Gao ': ' 888 '}


Delete a dictionary element

The deletion here refers to the display delete, which shows the deletion of a dictionary with the del command

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' before delete: ', student) #删除高爽del student[' Gao ']print (' after deletion: ', student)

C:\python\python.exe c:/python.py/zidian.py

Before deletion: {' Du Yuheng ': ' 666 ', ' Du Chaoli ': ' 999 ', ' Gao ': ' 888 ', ' Xu Wei ': ' 777 '}

After deletion: {' Du Yuheng ': ' 666 ', ' Du Chaoli ': ' 999 ', ' Xu Wei ': ' 777 '}

You can delete the entire dictionary in addition to the DELETE key

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}del studentprint (' after deleting the entire dictionary: ', student)

C:\python\python.exe c:/python.py/zidian.py

Traceback (most recent):

File "c:/python.py/zidian.py", line 8, <module>

Print (' after deleting the entire dictionary: ', student)

Nameerror:name ' student ' is not defined

Error: Student not defined

It can be seen from the above example that the dictionary cannot be accessed after the dictionary is deleted, and the dictionary does not exist after the Del operation.


Properties of Dictionary Keys

The ① key must be unavailable, can be used as a number, string, or tuple, and cannot be used in a list

The ② dictionary value can take any Pytho object without restriction, either as a standard object or as a user-defined object, but not a key.

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Yuheng ': ' 999 '}print (student)

C:\python\python.exe c:/python.py/zidian.py

{' Du Yuheng ': ' 999 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 '}

After a key has been assigned a value of two times, the following values are remembered


Len function

The Len function calculates the number of dictionary elements, that is, the total number of keys

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' The number of elements in the dictionary is:%d '%len (student) ')

C:\python\python.exe c:/python.py/zidian.py

The number of elements in a dictionary is: 4


type function

The type (variable) function returns the input variable types and returns the dictionary if the input variable is a dictionary

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' student ' type is: ', type (student))

C:\python\python.exe c:/python.py/zidian.py

The type of student is: <class ' dict ' >


formatting strings for Dictionaries

The dictionary is formatted with a key enclosed in parentheses after the% character in each conversion specifier, followed by other explanatory elements.

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' Xu Wei ' number is:% (Xu Wei) s '%student)

C:\python\python.exe c:/python.py/zidian.py

Xu Wei's number is: 777

Formatting the dictionary In addition to increasing the string, the conversion specifier works as before. When using a dictionary in this way, any number of conversion specifiers can be obtained as long as the given key can be found in the dictionary



The difference between a dictionary and a list

The dictionary (dict) is characterized by:

Finding and inserting is extremely fast and does not slow down as the key increases.

It takes a lot of memory and a lot of wasted memory.

The list is characterized by:

The find and insert times increase as the element increases.

Small footprint, less memory wasted

Note: The order in which the dict is stored inside is not related to the order in which the keys are placed.


Dictionary methods


Clera () method

The Clera () method is used to delete all items within the dictionary.

The Clera () method syntax is as follows:

Dict.clear ()

Dict represents a dictionary and does not require parameters. The function is a in-place operation (similar to the List.sort) function, with no return value (the return value is None)

The Clera () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' student ' element in Dictionary:%d '%len (student)) Student.clear () Print (' Student dictionary after deleting elements:%d '%len (student))

C:\python\python.exe c:/python.py/zidian.py

The elements in the student dictionary are: 4

Student the number of elements after the deletion of the dictionary is: 0

After the dictionary calls the clear method, all the items in the entire dictionary are deleted.


Copy method

The Copy method returns a new dictionary with the same key/value pairs. This method is shallow copy (shallow copy), because the value itself is the same, not a copy.

The Copy method syntax is as follows:

Dict.copy ()

DCT represents a dictionary and does not require parameters. Returns the result as a shallow copy of a dictionary

Copy Method Demo:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}st=student.copy () print (' The resulting st is: ', ST)

C:\python\python.exe c:/python.py/zidian.py

After copying the resulting St is: {' Du Chaoli ': ' 999 ', ' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 '}

What is shallow copy?

Example:

Student = {' Small wisdom ': ' 1002 ', ' info ': [' Xiao Zhang ', ' 1006 ', ' Man ']}st=student.copy () st[' little wise '] = ' 1005 ' Print (' change copy of St as: ', st) print ( ' Original string: ', student) st[' info '].remove (' Man ') print (' After delete St is: ', st) print (' Delete after student: ', student)

C:\python\python.exe c:/python.py/zidian.py

Change copy after the St is: {' info ': [' Xiao Zhang ', ' 1006 ', ' Man '], ' Little wisdom ': ' 1005 '}

The original string is: {' info ': [' Xiao Zhang ', ' 1006 ', ' Man '], ' Little wise ': ' 1002 '}

After deletion St is: {' info ': [' Xiao Zhang ', ' 1006 '], ' Little wisdom ': ' 1005 '}

After deletion student: {' info ': [' Xiao Zhang ', ' 1006 '], ' Little wisdom ': ' 1002 '}

From the example above, the original dictionary is not affected when you replace the value of the copy. If you modify a value (in-place modification, not a substitution), the original dictionary changes, because the same value is copied in this way in the original dictionary, which is shallow copy, and the problem can be avoided by using deep copy.

What is deep replication?

Example:

#深复制需要调用copy模块import copystudent = {' Little wisdom ': ' 1002 ', ' info ': [' Xiao Zhang ', ' 1006 ', ' Man ']}st=copy.deepcopy (student) st[' little wise '] = ' 1005 ' Print (' change after copy of St is: ', st) Print (' Original string: ', student) st[' info '].remove (' Man ') print (' After delete St is: ', st) print (' After deletion student: ', student)

C:\python\python.exe c:/python.py/zidian.py

After changing the copy the St is: {' Little wisdom ': ' 1005 ', ' info ': [' Xiao Zhang ', ' 1006 ', ' Man ']}

The original string is: {' Little wise ': ' 1002 ', ' info ': [' Xiao Zhang ', ' 1006 ', ' Man ']}

After deletion St is: {' Little wisdom ': ' 1005 ', ' info ': [' Xiao Zhang ', ' 1006 ']}

After deletion student: {' Small wisdom ': ' 1002 ', ' info ': [' Xiao Zhang ', ' 1006 ', ' Man ']}

Deep copy, which contains the copy of the object from the objects, so the change of the original object will not cause any change of the child elements in the deep copy.


Fromkeys () method

The Fromkeys () method is used to create a new dictionary, which is the key to the dictionary of the elements in the sequence SEQ, and value is the initial value corresponding to all the keys of the dictionary

The Fromkeys () method syntax is as follows:

Dict.fromkeys (Seq[,value])

The dict represents the specified dictionary; the EQ represents the Dictionary key value list; value represents an optional parameter, which sets the key sequence (seq). The method returns the result as a dictionary.

The Fromkeys () method demonstrates:

seq= (' name ', ' age ', ' sex ') info = dict.fromkeys (seq) print (' New dictionary:%s '% info) Info =dict.fromkeys (seq,10) print (' The Assigned Dictionary is: %s '%info)

C:\python\python.exe c:/python.py/zidian.py

The new dictionary is: {' name ': none, ' sex ': none, ' Age ': none}

The dictionary after assignment is: {' name ': ten, ' Sex ': ten, ' Age ': 10}

The Fromkeys () method creates a new dictionary with the keys for positioning, and each key defaults to a value of none.


Get () method

The Get () method returns the specified key value if the value is not in the dictionary and returns the default value.

The Get () method syntax is as follows:

Dict.get (Key,default=none)

The dict represents the specified dictionary, and the key represents the keys to be looked up in the dictionary, and the default indicates that the specified key value does not exist. The method returns the result to the specified key value, and returns the default value of None if the value is not in the dictionary.

The Get () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' Gao ' number is:%s '% student.get (' Gao ')) #访问一个不存在的键值print (' The number of firewood thriving is:%s '% student.get (' chai boom ')

C:\python\python.exe c:/python.py/zidian.py

Gao's School number is: 888

The number of firewood thriving is: None

When you use the Get method to access a nonexistent key, none is returned. You can customize the default values to replace None.

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '} #访问一个不存在的 key value when you replace the default return value of None with a custom value of print (' Wood boom number:%s '% Student.get (' Firewood thrives ', ' this person does not exist!!! ‘))

C:\python\python.exe c:/python.py/zidian.py

Wood prosperity of the school number is: This person does not exist!!

As can be seen from the above example, ' This person does not exist!!! ' Instead of none


Key in Dict () method

The key in Dict () method Python dictionary in operator is used to determine if the key exists in the dictionary, or False if the key returns true in the dictionary dict.

The key in Dict () method syntax is as follows:

Key in Dict

The dict represents the specified dictionary, and key represents the key to look up in the dictionary. Returns true if the key is in the dictionary dict, or False.

Key in Dict () method Demo: student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 ', ' Du Chaoli ': ' 999 '}print (' Du Yuheng in student dictionary? %s '% (' Du Yuheng ' in student)) print (' Is the wood thriving in the student dictionary? %s '% (' firewood thrives in ' student ')

C:\python\python.exe c:/python.py/zidian.py

Du Yuheng in the student dictionary? True

Does the wood thrive in the student dictionary? False

Note: There is a method Has_key method with the same function in Python2, and the Has_key method is used in different ways.


Items () method

The items () method returns an array of traversed (key, value) tuples in a list.

The items () method syntax is as follows:

Dict.items ()

The dict represents the specified dictionary, and no arguments are required. Returns the result as an array of (key/value) tuples that can be traversed.

The items () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}print (' result of calling the items method:%s '%student.items ())

C:\python\python.exe c:/python.py/zidian.py

Result of calling the items method: Dict_items ([' Du Yuheng ', ' 666 '), (' Xu Wei ', ' 777 ')])

The previous example shows that the returned result is a tuple group number.

Note: A Iteritems method is provided in Python2, and the items method works roughly the same, but the Iteritems method returns an iterator object instead of a list. There is no Iteritems method in Python3


Keys () method

The keys () method returns all keys for a dictionary in a list.

The keys () method syntax is as follows;

Dict.keys ()

The dict represents the specified dictionary, and no arguments are required. Returns the result as a dictionary of all keys.

The keys () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}print ("All keys in the student dictionary are:%s"%student.keys ())

C:\python\python.exe c:/python.py/zidian.py

All keys in the student dictionary are: Dict_keys ([' Du Yuheng ', ' Xu Wei '])

The previous example shows that a tuple is returned, and the array contains all the keys of the dictionary.


SetDefault () method

The SetDefault () method is similar to the Get () method for obtaining the value associated with a given key. If the key does not exist in the dictionary, the key is added and the value is set to the default value.

The SetDefault () method syntax is as follows:

Dict.setdefault (Key.default=none)

The dict represents the specified dictionary; key represents the key value of the lookup, and the default represents the value that is set when it does not exist. The method does not have any return value.

The SetDefault () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}print (' Gao ' key value:%s '%student.setdefault (' Gao ')) ' Print (' Xu Wei ' key value:%s '% Student.setdefault (' Xu Wei ')) print (' Student dictionary with type value:%s '%student)

C:\python\python.exe c:/python.py/zidian.py

The key value for the GAO is: None

The key value of the Xu Wei is: 777

The type value of the student dictionary is: {' Xu Wei ': ' 777 ', ' Gao ': None, ' Du Yuheng ': ' 666 '}

As can be seen in the example above, the SetDefault () method returns the default value and updates the dictionary when the key does not exist, and returns the corresponding value if the key exists, without changing the dictionary.

When using SetDefault () to access a nonexistent key value, use None if not set, if set to use the set value.

For example:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}print (' Gao ' key value:%s '%student.setdefault (' Gao '))

C:\python\python.exe c:/python.py/zidian.py

The key value for the GAO is: None

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}print (' Gao ' key value:%s '%student.setdefault (' Gao ', ' 888 ')) print (student)

C:\python\python.exe c:/python.py/zidian.py

The key value of the GAO is: 888

{' Gao ': ' 888 ', ' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}

As shown above, the output is none when the default value is used, the key value is set and the dictionary is updated.


Update method () method

The Update method () method updates the key value/value pairs of the dictionary dict2 to the Dict

The Update method () method syntax is as follows:

Dict.update (DICT2)

Dict represents the specified dictionary; Dict2 represents the dictionary added to the specified dictionary dict. The method does not have any return value.

The Update method () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}student2={' Gao ': ' 888 '}print (' original Student Dictionary:%s '%student) student.update (Student2) Print (' New Student Dictionary:%s '%student) #对相同项覆盖student3 ={' Gao ': ' 1010 '}student.update (student3) print (' New Student dictionary after overwrite:%s ') %student)

C:\python\python.exe c:/python.py/zidian.py

The original student dictionary is: {' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 '}

The new Student Dictionary is: {' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 888 '}

The new Student dictionary after overwriting is: {' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 1010 '}

As can be seen from the previous example, the items in the provided dictionary are added to the old dictionary and overwritten if the same key is available.


Values () method

The values () method returns all the values in the dictionary as a list, unlike the list of returned keys, which can contain duplicate elements in the list.

The values () method syntax is as follows:

Dict.values ()

The dict represents the specified dictionary, and no arguments are required. Returns the result as all values in the dictionary.

The values () method demonstrates:

student={' Du Yuheng ': ' 666 ', ' Xu Wei ': ' 777 ', ' Gao ': ' 666 '}print ("Student Dictionary All Values are:%s"%list (Student.values ()))

C:\python\python.exe c:/python.py/zidian.py

Student dictionary All values are: [' 666 ', ' 666 ', ' 888 ']

As you can see in the previous example, the returned list contains duplicate elements.


This article from "Duyuheng" blog, declined reprint!

Handbook of python3.5 cultivation 10

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.