Python dictionaries and collections
1. Addition, deletion and modification of dictionary
1. Additions and modifications
When the [dictionary value] key exists; Add a key value pair when the key does not exist
Dictionaries. SetDefault (key, value) -- add a key value pair when the key does not exist, and do not change when the key exists
cat = {'name': 'to one's heart's content', 'age': 2, 'color': 'white'} print(cat) # {'name': 'Meimei', 'age': 2, 'color': 'white'}
add to
cat['bread'] = 'Blue cat' print(cat) # {'name': 'Meimei', 'age': 2, 'color': 'white', 'bread': 'blue cat'} cat.setdefault('weight', 5) print(cat) # {'name': 'Meimei', 'age': 1, 'color': 'white', 'bread': 'blue cat', 'weight': 5} cat.setdefault('age', 4) print(cat) # {'name': 'Meimei', 'age': 1, 'color': 'white', 'bread': 'blue cat', 'weight': 5}
modify
cat['age'] = 1 print(cat) # {'name': 'Meimei', 'age': 1, 'color': 'white', 'bread': 'blue cat'}
Exercise: add the key value pair corresponding to the score to the students who have no score in the students, and the score value is zero
students = [ {'name': 'stu1', 'tel': '1234', 'score': 89}, {'name': 'stu2', 'tel': '465', 'score': 80}, {'name': 'stu3', 'tel': '678'}, {'name': 'stu3', 'score': 78}, {'name': 'stu4', 'tel': '234'} ] for x in students: x.setdefault('score', 0) print(students)
2. Delete -- delete key value pairs
del DICTIONARY [key] - delete the key value pair corresponding to the specified key in the dictionary (an error will be reported if the key does not exist)
Dictionaries. Pop (key) -- take out the value corresponding to the specified key in the dictionary (an error will be reported if the key does not exist)
print(cat) # {'name': 'Meimei', 'age': 1, 'color': 'white', 'bread': 'blue cat', 'weight': 5} del cat['color'] print(cat) # {'name': 'Meimei', 'age': 1, 'bread': 'blue cat', 'weight': 5} new_cat = cat.pop('bread') print(cat) # {'name': 'Meimei', 'age': 1, 'weight': 5} print(new_cat) # Blue cat
2. Dictionary related operations and functions
1. Related operations
The dictionary does not support +, -, *, nor does it support size comparison operators. It only supports = ==
Support in and not in (judge whether the key exists)
Key in dictionary
Key not in dictionary
dic1 = {'a': 10, 'b': 20, 'c': 30} print(10 in dic1) # False print('a' in dic1) # True
2. Correlation function
len -- number of key value pairs
Dict (data) -- type conversion
The data itself is a sequence;
Elements in a sequence must have a small sequence of only two elements
The first element of a small sequence must be immutable data
Convert dictionary to list and tuple
data = [('a', 11), ('b', 22)] print(dict(data)) # {'a': 11, 'b': 22} data2 = ['ab', range(2), [10, 20]] print(dict(data2)) # {'a': 'b', 0: 1, 10: 20} dic1 = {'a': 10, 'b': 20, 'c': 30} print(list(dic1)) # ['a', 'b', 'c']
3. Dictionary related methods
Dictionaries. clear() -- clear
Dictionaries. As like as two peas, copy() - copy the original dictionary to produce a new dictionary that is exactly the same.
Dictionaries. update (sequence) -- add all elements in the sequence to the dictionary (overwrite if they exist). The sequence must be a dictionary or a sequence that can be converted to a dictionary.
Dictionaries. items() -- get the key value pair in the dictionary and return a sequence. The key value pair will become a tuple
Dictionaries. keys() -- get all the keys in the dictionary and return a sequence
Dictionaries. values() -- get all the values of the dictionary and return a sequence
dic1.update(data) print(dic1) # {'a': 11, 'b': 22, 'c': 30} print(dic1.keys()) # dict_keys(['a', 'b', 'c']) print(dic1.items()) # dict_items([('a', 11), ('b', 22), ('c', 30)]) print(dic1.values()) # dict_values([11, 22, 30])
4. Dictionary derivation
{key expression: value expression for variable in sequence}
{expression of key: expression of value for variable in sequence if conditional statement}
# Exercise: exchange the keys and values of a dictionary through the derivation of a dictionary # {'a': 11, 'b': 22, 'c': 30}--{ 11:'a', 22:'b', 30:'c' } dic3 = {'a': 10, 'b': 20} new_dic3 = {dic3[key]: key for key in dic3} print(new_dic3)
3. Assemble
1. What is a collection
A collection is a container; Take {} as the container flag, and multiple elements are separated by commas: {element 1, element 2, element 3,...}
The set is variable; The set is out of order;
Element: immutable data, element is unique (with automatic de duplication function)
# 1) Empty set ste1 = set() print(type(ste1), len(ste1)) # <class 'set'> 0 # 2) The collection is out of order print({1, 2, 3} == {2, 3, 1}) # True # 3) The element must be immutable data ste2 = {1, 'asd', (2, 3)} print(ste2) # {(2, 3), 1, 'asd'} # ste3 = {1,'asd',[2,3]} # report errors # print(ste3) # 4) Element is unique ste4 = {1, 2, 3, 4, 5, 3, 2, 1} print(ste4) # {1, 2, 3, 4, 5}
2. Addition, deletion, modification and query of set elements
1) Search traversal
for element in set:
Circulatory body
2) Increase
Assemble Add (element) - adds the specified element to the collection
Assemble update - adds all the elements in the sequence to the collection
3) Delete
Assemble remove (element) -- delete the specified element. If the element does not exist, an error will be reported
Assemble discard (element) -- delete the specified element. If the element does not exist, no error will be reported, and the original set will be output
4) Change -- the collection cannot directly modify the value of an element. You can only delete the element to be changed and add a new one
nums = {23, 24, 45, 67} for x in nums: print(x) ''' 24 67 45 23 ''' nums.add(33) print(nums) # {33, 67, 45, 23, 24} nums.update('asd') print(nums) # {33, 67, 's', 45, 'a', 23, 24, 'd'} nums.remove(33) print(nums) # {67, 'd', 45, 's', 'a', 23, 24} nums.discard(5) print(nums) # {'a', 67, 45, 's', 'd', 23, 24} nums.discard('a') nums.add('A') print(nums) # {'A', 67, 's', 45, 'd', 23, 24}
3. Mathematical set operations: & (intersection), | (Union), - (difference set), ^ (symmetric difference set), > / < (true subset), > = / < = (subset)
nums1 = {1, 2, 3, 4, 5, 6, 7} nums2 = {5, 6, 7, 8, 9} # 1) Set 1 & Set 2 - get the common elements of two sets (get the elements in both set 1 and set 2) print(nums1 & nums2) # {5, 6, 7} # 2) Set 1 | set 2 - gets all the elements of both sets print(nums1 | nums2) # {1, 2, 3, 4, 5, 6, 7, 8, 9} # 3) Set 1 - Set 2 - gets the part of set 1 other than contained in set 2 print(nums1 - nums2) # {1, 2, 3, 4} print(nums2 - nums1) # {8, 9} # 4) Set 1 ^ set 2 - merge two sets, removing the middle common part print(nums1 ^ nums2) # {1, 2, 3, 4, 8, 9} # 5) Subset (possibly equal) and true subset (really smaller than it) # Set 1 > Set 2 - > judge whether set 2 is a true subset of set 1 print({10, 20, 30, 40} > {1, 2}) # False print({10, 20, 30, 40} > {10, 40}) # True print({10, 20, 30, 40} > {10, 20, 30, 40}) # False print({10, 20, 30, 40} >= {10, 20, 30, 40}) # True
practice
-
Define a list and save the information of 6 students in the list (student information includes: name, age, grade (single subject), telephone, gender (male, female, unknown))
students=[ {'name': 'stu1', 'age': 18,'gender':'male', 'tel': '1123', 'score': 98}, {'name': 'stu2', 'age': 20,'gender':'female', 'tel': '8999', 'score': 76}, {'name': 'stu3', 'age': 28,'gender':'male', 'tel': '6788', 'score': 53}, {'name': 'stu4', 'age': 16,'gender':'Unknown', 'tel': '9900', 'score': 87}, {'name': 'stu5', 'age': 19,'gender':'male', 'tel': '6658', 'score': 71}, {'name': 'stu6', 'age': 18,'gender':'Unknown', 'tel': '8920', 'score': 90} ]
-
Count the number of failed students
n = 0 for x in students: if x.get('score') < 60: n += 1 print(n)
-
Print the names of the failed students and the corresponding grades
for x in students: if x.get('score') < 60: print(x.get('name'), x.get('score'))
-
Print the name of the student whose mobile phone tail number is 8
for x in students: if int(x.get('tel')) % 10 == 8: print(x.get('name'))
-
Print the highest score and the corresponding student's name
max_score = students[0].get('score') name = [] for x in students: if x.get('score') > max_score: max_score = x.get('score') name.clear() name.appendx.get('name') else max_score == x.get('score'): name.appendx.get('name') print('Highest score:',max_score,'Name of the corresponding student',name )
-
Delete all students of Unknown Gender
for x in students.copy(): if x.get('gender')=='Unknown': students.remove(x) print(students) # Method 2: new_student = [x for x in students if x.get('gender') != 'Unknown'] print(new_student)
-
Sort the list according to the students' grades (struggle, give up if you can't)
student_list.sort(key=lambda item: item['score'], reverse=True) print(student_list)
-
-
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)
natural ={'Zhang San','Li Si','Wang Wu','Yan Xiaoliu','Small ten'} music = {'Junior one','waiter','Small eight','Li Si','Small ten'} movie = {'seven seven','multiplication table','zero zero','Small ten'}
-
How many students are there in total
n =[] for x in natural: n.append(x) for y in music: if y not in n: n.append(y) for z in movie: if z not in n: n.append(z) print(len(n))
-
Find the number of people who only selected the first subject and their corresponding names
n =[] for x in natural: n.append(x) for y in music: if y in n: n.remove(y) for z in movie: if z in n: n.remove(z) print(n)
-
Find the number of students who have chosen only one subject and their corresponding names
n = natural^music^movie print(len(n),n)
-
Find the number of students who have chosen only two subjects and their corresponding names
n = natural & music & movie a = natural & movie b = natural & music c = movie & music m = a | b | c for x in n: m.discard(x) print(len(m), m)
-
Find the number of students who have selected three courses and their corresponding names
n=natural&music&movie print(len(n),n)
-