This article mainly introduces how to use dict and set in Python. It is the basic knowledge of getting started with Python. If you need it, you can refer to the list of arrays similar to PHP in Python, tuple, dict, and set, where list, tuple, and set are similar to PHP index arrays, while dict is similar to PHP associated arrays,
Dict:
The structure of dict represents a ing relationship, which is similar to the associated array of PHP. For example, to define a user information:
name: Yi_Zhi_Yusex: Mancountry: China
The use of list, tuple, and set cannot be expressed directly, because the string cannot be used as the key-value structure, and dict can, as shown below:
M = {"name": "Yi_Zhi_Yu", "sex": "Man", "country": "China"} // note that here is '{}', not '[]' print m ["name"] // Yi_Zhi_Yuprint m ["sex"] // Manprint m ["country"] // China
The value object of dict has a get method, so that we can specify the default value when getting the specified key.
- Dict is advantageous in searching (hash key) and inserting (with no sequential Requirements) speed, but it consumes a large amount of memory.
- The list is the opposite.
Set:
Set is similar to List and Tuple, but the values in Set are not repeated.
For example, to define a course, use set definition:
Definition:
Classes = set ([u "", u "", u ""]) // set keyword, listprint classes // set ([U' \ u8bed \ u6587 ', U' \ u6570 \ u5b66', U' \ u82f1 \ u6587 '])
Add
Classes. add (u "Mathematics ")
// No repeated print classes // set ([U' \ u8bed \ u6587 ', U' \ u6570 \ u5b66', U' \ u82f1 \ u6587 ']) classes. add (u "History") print classes // set ([U' \ u8bed \ u6587 ', U' \ u6570 \ u5b66', U' \ u5386 \ u53f2 ', u' \ u82f1 \ u6587 '])
The delete method is remove:
Classes. remove (u "History") print classes // set ([U' \ u8bed \ u6587 ', U' \ u6570 \ u5b66', U' \ u82f1 \ u6587 '])