day8 - dictionaries and collections
1 dictionary related operations and methods
1. The dictionary does not support addition, mu lt iplication and >, <, > =<=
2. Dictionary support = ==
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})
3.in and not in
Key in dictionary ---- judge whether the specified key exists in the dictionary
d1 = {'a': 10, 'b': 20, 'c': 30} print(30 in d1) # False print('b' in d1) # True
4. Type conversion dict
""" dict(data) - Convert data into a dictionary Data requirements: 1) the data itself is a sequence 2)Elements in a sequence must be small sequences of length 2 3)The first element of a small sequence must be immutable data """
result = dict([(1,2), 'ab',['b', 100]]) print(result) # {1: 2, 'a': 'b', 'b': 100}
Note: when converting a dictionary into a list or tuple, use the key of the dictionary as the element in the list or tuple
d1 = {'a': 10, 'b': 20, 'c': 30} print(list(d1)) # ['a', 'b', 'c'] print(tuple(d1)) # ('a', 'b', 'c')
5. Relevant methods
1) dictionary. clear() - clear the dictionary
d1 = {'a': 10, 'b': 20, 'c': 30} print(d1.clear()) # {}
2) dictionary. copy() - Clone
stu1 = {'name': 'Xiao Ming', 'gender':'male', 'age': 19} stu2 = stu1.copy() print(stu2) # {'name': 'Xiao Ming', 'gender': 'male', 'age': 19} stu2['name'] = 'Zhang San' # Modify the value corresponding to the key name of the cloned stu2 to Zhang San print(stu2) # {'name': 'Zhang San', 'gender': 'male', 'age': 19} print(stu1) # {'name':'xiaoming ',' gender ':'male','age': 19} because of cloning, the content in stu1 remains unchanged
3) dictionary. get() - get value by building
4) dictionary. items() - convert the elements in the dictionary into tuples and return a new sequence
# {key 1: value 1, key 2: value 2} -- > [(key 1, value 1), (Key 2, value 2)] stu1 = {'name': 'Xiao Ming', 'gender':'male', 'age': 19} result = stu1.items() print(type(result)) # <class 'dict_items'> print(result) # dict_items([('name ',' Xiaoming '), ('gender', 'male'), ('age', 19)])
# Dictionary derivation: {key value pair for variable in sequence}, {key value pair for variable in sequence if condition} # Exercise: using list derivation, multiply all the values of a dictionary by 10 d2 = {'a': 2, 'b': 34, 'c': 21} # {'a': 20, 'b': 340, 'c': 210} # Method 1 d3 = {key: value*10 for key, value in d2.items()} print(d3) # # {'a': 20, 'b': 340, 'c': 210} # Method 2 d3 = dict([key, value*10] for key, value in d2.items()) print(d3) # # {'a': 20, 'b': 340, 'c': 210} # Method 3 d3 = {x:d2[x]*10 for x in d2} print(d3) # # {'a': 20, 'b': 340, 'c': 210}
# Use dictionary derivation to exchange dictionary keys and values d2 = {'a': 2, 'b': 34, 'c': 21} # {2: 'a', 34: 'b', 21: 'c'} d3 = {value: key for key, value in d2.items()}
5) dictionary. key() - get all the keys in the dictionary and return a new sequence
d2 = {'a': 2, 'b': 34, 'c': 21} print(d2.key()) # dict_keys(['a', 'b', 'c'])
6) dictionary. values() - get all the values of the dictionary and return a new sequence
d2 = {'a': 2, 'b': 34, 'c': 21} print(d2.values()) # dict_values([2, 34, 21])
7) dictionary. SetDefault (key, value) - add a key value pair to the dictionary. If the key value pair already exists in the dictionary, the modification operation will not be performed. If it does not exist, it will be added
# DICTIONARY [key] = value - modify the value corresponding to the key when the modification exists, or add if it does not exist d2 = {'a': 2, 'b': 34, 'c': 21} d2.setdefault('c', 23) print(d2) # {'a': 2, 'b': 34, 'c': 21}
# practice goods_list = [ {'name': 'Instant noodles', 'price': 4, 'discount': 0.9, 'count': 100}, {'name': 'Ham sausage', 'price': 2, 'count': 120}, {'name': 'mineral water', 'price': 1, 'count': 500}, {'name': 'bread', 'price': 5, 'count': 120, 'discount': 0.75} ] for good in goods_list: good.setdefault('discount', 1) print(goods_list)
8) dictionary. Update (sequence) - add all the elements in the sequence to the dictionary
Sequence - is a dictionary or a sequence that can be converted into a dictionary
d1 = {'a': 10, 'b': 20} d2 = {'name': 'Xiao Ming', 'age': 19, 'a': 100} d1.update(d2) print(d1) # {'a': 100, 'b': 20, 'name': Xiaoming ',' age': 19} d1.update(['mn',(1, 2)]) print(d1) # # {'a': 100, 'b': 20, 'name': Xiaoming ',' age ': 19,'m': n ', 1: 2}
2 set
1. What is a set
A collection is a container data type (sequence). It takes {} as the flag of the container, and multiple elements in it are separated by commas: {element 1, element 2, element 3,...}
Features of collections as containers: collections are variable (support addition, deletion and modification), and unordered (do not support subscript operations)
Set requirements for elements: 1) must be immutable data; 2) Must be unique
# 1) Empty set s1 = set() print(s1, type(s1)) # {} <class 'set'> print(len(s1)) # 0
#2) Collection elements must be immutable data set2 = {1, 'a', (1, 3)} print(set2) # {1, (1, 3),'a '} (because the set is disordered, there is no order)
# 3) Set disorder print({1, 2, 3} == {2, 3, 1}) # True (because the collection is unordered)
# 4) Element is unique set3 = {1, 2, 3, 1, 2, 4, 3, 5} print(set3) # {1, 2, 3, 4, 5}
2. Addition, deletion and modification of collections
# 1) Query - can only traverse hobby = {'play a game', 'watch movie', 'Play basketball', 'Mountain climbing', 'cook'} for x in hobby: print(x, end=' ') # Play games, cook, climb mountains, watch movies and play basketball
# 2) Increase # Set. Add (element) # Set. Update (sequence) hobby = {'play a game', 'watch movie', 'Play basketball', 'Mountain climbing', 'cook'} hobby.add('Swimming') print(hobby) # 'play games',' cook ',' swim ',' climb mountains', 'Watch Movies',' play basketball '} hobby.update(('Table tennis','badminton')) print(hobby) # {'play games',' table tennis', 'cook', 'badminton', 'swim', 'climb mountains',' Watch Movies', 'play basketball'}
# 3) Delete # Set. Remove (element) - an error will be reported if the element does not exist # Set. Discard (element) - if the element does not exist, no error will be reported and no exception will be caught hobby.remove('cook') print(hobby) # {'table tennis',' swimming ',' mountain climbing ',' watching movies', 'badminton', 'playing games',' playing basketball '} hobby.discard('play a game') # # {'swimming', 'watching movies',' playing basketball ',' badminton ',' mountain climbing ',' table tennis'}
3 mathematical set operation
1. Sets in Python support mathematical set operations
1) union:|
Set 1 | set 2 ------- merge two sets into one set
s1 = {1, 2, 3, 4, 5, 6} s2 = {4, 5, 6, 7, 8} print(s1 | s2) # {1, 2, 3, 4, 5, 6, 7, 8}
2) intersection:&
Set 1 & Set 2 ---- get the common parts of two sets and generate a new set
s1 = {1, 2, 3, 4, 5, 6} s2 = {4, 5, 6, 7, 8} print(s1 & s2) # {4, 5, 6}
3) difference set:-
Set 1 - Set 2 ---------- get the remaining elements in set 1 after removing the elements in set 2
s1 = {1, 2, 3, 4, 5, 6} s2 = {4, 5, 6, 7, 8} print(s1 - s2) # {1, 2, 3} print(s2 - s1) # {7, 8}
4) symmetric difference set:^
Set 1 ^ set 2 ---- merge the two sets, remove the common part, and get the rest
s1 = {1, 2, 3, 4, 5, 6} s2 = {4, 5, 6, 7, 8} print(s1 ^ s2) # {1, 2, 3, 7, 8}
5) judge subset relationship
Subset: > =<=
True subset: ><
Set 1 > Set 2 ---- judge whether set 2 is a true subset of set 1
Set 1 < set 2 ---- judge whether set 1 is a true subset of set 2
s3 = {10, 20, 30} # True subset: {10}, {20}, {30}, {10,20}, {10,30}, {20,30}, empty set # Subset: {10}, {20}, {30}, {10,20}, {10,30}, {20,30}, empty set, {10, 20, 30} print({100, 200, 300} > {1, 2,3}) # False print({100, 200, 300} > {100}) # True
# practice: # Use three sets to represent the names of students who choose courses in three disciplines (a student can choose multiple courses at the same time) course1 = {'floret', 'Xiao Ming', 'Xiao Zhang', 'cockroach', 'Xiaohua', 'Xiao Chen'} course2 = {'Xiao Zhang', 'Xiao Wang', 'Xiao Ming', 'Xiao Bi', 'Xiao Fang', 'Xiao Chen'} course3 = {'floret', 'Xiao Ming', 'Xiao Zhang', 'Xiao Su', 'Xiao Wang', 'Xiao Chen'} print('----------------1-------------------') # 1. How many students are there in total course_num = course1 | course2 | course3 print('There are a total of students in the course selection:', len(course_num)) print('-----------------------2--------------') # 2. Find the number of people who have selected only the first discipline and their corresponding names course_c1 = course1 - course2 - course3 print('Number of people who chose only the first subject:', len(course_c1)) print('Who chose only the first subject:', course_c1) print('-----------------------5--------------') # 5. Find the number of students who have selected three courses and their corresponding names course_3 = course1 & course2 & course3 print('Number of people who chose three subjects:', len(course_3)) print('Names of people who chose three subjects:', course_3) print('-----------------------3--------------') # 3. Find the number of students who have chosen only one subject and their corresponding names # Method 1 course_1 = (course1 - course2 - course3) | (course2 - course1 -course3) | (course3 - course1 -course2) print('The number of people who chose only one subject:', len(course_1)) print('The name of the person who chose only one subject:', course_1) # Method 2 course_1 = course1 ^ course2 ^ course3 - course_3 print('The number of people who chose only one subject:', len(course_1)) print('The name of the person who chose only one subject:', course_1) print('-----------------------4--------------') # 4. Find the number of students who have only selected two subjects and their corresponding names # Method 1 course_2 = (course1 & course2 - course3) | (course2 & course3 - course1) | (course1 & course3 - course2) print('The number of people who chose only two subjects:', len(course_2)) print('The names of people who chose only two subjects:', course_2) # Method 2 course_2 = course_num - course_3 - course_1 print('The number of people who chose only two subjects:', len(course_2)) print('The names of people who chose only two subjects:', course_2)