I. Python 3 dictionary
A dictionary is another variable container model and can store any type of object
Each key value pair of the dictionary is divided by a colon ':', and each key value pair is divided by a comma ','. The whole dictionary is included in the curly bracket '{}'. The format is as follows:
dict = {key1:value1,key2:value2,......,keyN:valueN}
Be careful:
The key must be unique, but the value does not have to be
The value can take any data type, but the key must be immutable, such as string, number or tuple
1. Create a dictionary
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(dict) //The output result is: {'name': 'lrving', 'gender': 'boy', 'age': 23, 'identity': 'student', 'university': 'tsinghua'}
2. Access to the values in the dictionary
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(dict['name']) #Access the value of key name in dict print(dict['age']) #Access the value of key age in dict //The output result is: lrving 23
3. Modify dictionary
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(dict) dict['age'] = 20 #Update value of key age dict['university'] = 'Peking University' #Update the value of key university print(dict) //The output result is: {'name': 'lrving', 'gender': 'boy', 'age': 23, 'identity': 'student', 'university': 'tsinghua'} {'name': 'lrving', 'gender': 'boy', 'age': 20, 'identity': 'student', 'university': 'Peking University'}
4. Delete dictionary elements
Can delete a single element can also empty the dictionary, empty only one operation
4.1 delete a single key
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} del dict['university'] #Delete key university print(dict) //The output result is: {'name': 'lrving', 'gender': 'boy', 'age': 23, 'identity': 'student'}
4.2 clear dictionary
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} dict.clear() #Empty dictionary print(dict) //The output result is: {}
4.3 delete dictionary
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} del dict print(dict) //The output is: (but this raises an exception because the dictionary no longer exists after del operation is performed with) Traceback (most recent call last): File "/Users/liwenfeng/PycharmProjects/Python/study.py", line 157, in <module> print(dict['name']) TypeError: 'type' object is not subscriptable
Description dictionary dict has been deleted
5. Characteristics of dictionary key
The dictionary value can be any python object, either standard or user-defined, but the key cannot
Two important points to remember:
5.1. The same key is not allowed to appear twice in a dictionary. When creating a dictionary, if the same key is assigned twice, only the following values are recognized. The example is as follows:
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','age':34,'name':'james'} #The key name and age appear twice print(dict) //The output result is: {'name': 'james', 'gender': 'boy', 'age': 34, 'identity': 'student'} #You can see that the key name and age only recognize the next two values, james and 34
5.2. The key must be immutable, so it can be used as a number, string and tuple, while the list is not feasible, as shown in the following example:
dict = {['name']:'lrving','gender':'boy',['age']:23} print(dict['name']) //The output result is: Traceback (most recent call last): File "/Users/liwenfeng/PycharmProjects/Python/study.py", line 158, in <module> dict = {['name']:'lrving','gender':'boy',['age']:23} TypeError: unhashable type: 'list'
It can be seen that it is not feasible to use lists in dictionaries
6. Dictionary built-in functions & Methods
6.1 len(dict): count the number of dictionary elements, that is, the total number of keys
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(len(dict)) //The output result is: 5
6.2 str(dict): output dictionary, represented by printable string
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(str(dict)) //The output result is: {'name': 'lrving', 'gender': 'boy', 'age': 23, 'identity': 'student', 'university': 'tsinghua'}
6.3. type(variable): returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type
dict = {'name':'lrving','gender':'boy','age':23,'identity':'student','university':'tsinghua'} print(type(dict)) //The output result is: <class 'dict'>
7. The Python dictionary contains the following built-in methods
7.1,radiansdict.clear()
Delete all elements in dictionary
7.2,radiansdict.copy()
Returns a shallow copy of a dictionary
7.3,radiansdict.fromkeys()
Create a new dictionary, use the elements in sequence seq as the key of the dictionary, val is the initial value corresponding to all keys of the dictionary
7.4,radiansdict.get(key, default=None)
Returns the value of the specified key, or the default value if the value is not in the dictionary
7.5,key in dict
If the key returns true in the dictionary dict, otherwise it returns false
7.6,radiansdict.items()
Returns a traversable (key, value) tuple array as a list
7.7,radiansdict.keys()
Returns an iterator that can be converted to a list using "list()"
7.8,radiansdict.setdefault(key, default=None)
Similar to get(), but if the key does not exist in the dictionary, the key is added and the value is set to default
7.9,radiansdict.update(dict2)
Update key / value pairs of dict2 to Dict
7.10,radiansdict.values()
Returns an iterator that can be converted to a list using "list()"
7.11,pop(key[,default])
Delete the value corresponding to the key given in the dictionary. The return value is the value to be deleted. The key value must be given. Otherwise, the default value is returned
7.12,popitem()
Randomly return and delete the last pair of keys and values in the dictionary
II. Python 3 collection
Set is an "unordered sequence of distinct elements"
If there are two or more identical elements in the set, only one (de duplication) will be taken when the value is taken
You can use braces' {} 'or' set() 'functions to create a collection. Note: to create an empty collection, you must use' set() 'instead of' {} ', because' {} 'is used to create an empty dictionary
1. Create a collection
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} b = set('lrving11curry30klay11') print(a) print(b) //The output result is: {'kobe', 'heat', 'AD', 'wade', '3', 23, 'james', 'lakers'} {'n', 'g', '1', 'a', 'u', 'k', '0', 'l', 'i', 'v', '3', 'r', 'c', 'y'}
2. Set operation
a = set('cbdcjdsuac') b = set('ejciaugejasye') print(a) print(b) print(a - b) #Elements contained in a but not contained in b print(b - a) #Elements contained in b but not contained in a print(a | b) #Union of a and b print(a & b) #Intersection of a and b print(a ^ b) #Elements that do not contain both a and b //The output result is: {'c', 'u', 'a', 's', 'j', 'b', 'd'} {'u', 'a', 's', 'y', 'j', 'e', 'i', 'c', 'g'} {'b', 'd'} {'i', 'y', 'g', 'e'} {'i', 'c', 'g', 'u', 'a', 's', 'y', 'j', 'e', 'b', 'd'} {'u', 'a', 's', 'j', 'c'} {'b', 'y', 'e', 'i', 'd', 'g'}
2.1. Similar to list derivation, the same set supports set derivation
a = {x for x in 'abracadabra' if x not in 'abc'} print(a) //The output result is: {'d', 'r'}
3. Basic operation of collection (add;update)
3.1. Add an element to a collection
Method 1:
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.add('NBA') print(a) //The output result is: {'heat', 'kobe', 'NBA', 'lakers', 'AD', 'wade', 'james', '3', 23}
Method two:
You can add elements, and parameters can be lists, tuples, dictionaries, etc. the syntax format is as follows
a.update(x) #"x" can have multiple, separated by commas
Example:
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.update([1,'lrving','Antetokounmpo']) #Add a list to the collection a.update((2,'six','five')) #Add a tuple to the set a.update({'name':'Howard'}) #When you add a dictionary to a collection, only the key of the dictionary is added, not the value of the key print(a) //The output result is: {1, 'heat', 2, 'name', 'Antetokounmpo', 'five', 'AD', 'wade', 'kobe', 'lrving', 'six', 'lakers', 23, 'james', '3'}
3.2 remove, discard, pop
Method 1:
Syntax format:
a.remove(x) #Remove element 'x' from collection 'a', error if element does not exist
Example:
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.remove("heat") print(a) //The output result is: {'3', 'kobe', 'james', 23, 'lakers', 'wade', 'AD'}
Method two:
Syntax format:
a.discard(x)
Example:
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.discard('heat') a.discard('Cleveland') #When the overridden element does not exist in the collection, no error will be reported print(a) //The output result is: {'3', 'james', 'lakers', 'wade', 23, 'kobe', 'AD'}
Method three:
Syntax format:
a.pop() #This method is to randomly delete an element in a set
Example:
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.pop() print(a) The output result is: (this result is the result of two consecutive executions) {'Kobe','wade ','ad','james', 23, 'heat','ladies'} the element '3' has been deleted The element 'AD' has been deleted
Note: in interactive mode, this method is to delete the first element of the collection ---- remember! Remember! Remember!
3.3. Count the number of set elements
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} print(len(a)) //The output result is: 8
4. Clear the set
Syntax format:
a.clear()
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} a.clear() print(a) The output result is: set()
5. Judge whether the element exists in the set
Grammatical format:
x in a #Returns True and false
a = {'lakers','james',23,'heat','wade','3','kobe','AD'} print('cleveland' in a) print(23 in a) //The output result is: False True
6. Complete list of set built-in methods
6.1,add()
Adding elements to a collection
6.2,clear()
Remove all elements from the collection
6.3,copy()
Copy a collection
6.4,difference()
Returns the difference set of multiple sets
6.5,difference_update()
Removes an element from a collection that also exists in the specified collection
6.6,discard()
Delete the specified element in the collection
6.7,intersection()
Returns the intersection of sets
6.8,intersection_update()
Returns the intersection of sets
6.9,isdisjoint()
Determines whether two sets contain the same elements. If True is not returned, False is returned
6.10,issubset()
Determine whether the specified set is a subset of the method parameter set
6.11,issuperset()
Determine whether the parameter set of the method is a subset of the specified set
6.12,pop()
Randomly remove elements
6.13,remove()
Remove specified element
6.14,symmetric_difference()
Returns a set of elements that are not duplicated in two sets
6.15,symmetric_difference_update()
Removes the same elements from the current collection in another specified collection, and inserts different elements from another specified collection into the current collection
6.16,union()
Returns the union of two sets
6.17,update()
Add elements to a collection