2.23 Summary - dictionaries, assignments
1. Cognitive Dictionary (dict)
-
Is a container data type; Take {} as the flag of the container, in which multiple key value pairs are separated by commas: {key 1: value 1, key 2: value 2, key 3: value 3,...}
Key value pair: key value -
The dictionary is changeable (support addition, deletion and modification); The dictionary is out of order (subscripts are not supported, and the order of elements does not affect the result)
-
Requirements for elements
Dictionary elements are key value pairs
a. Key requirements: the key must be immutable type of data (data, string, Boolean, tuple, etc.); Key is unique
b. Value requirement: no requirement
2. Look up - get the value of the dictionary
-
Check single (important) - get one value at a time
Syntax 1: Dictionary [key] - get the value corresponding to the specified key in the dictionary; If the key does not exist, an error will be reported
Syntax 2:
Dictionaries. Get (key) - get the value corresponding to the specified key in the dictionary; If the key does not exist, no error will be reported and None will be returned
Dictionaries. Get (key, default value) - get the value corresponding to the specified key in the dictionary; If the key does not exist, the default value is returned -
ergodic
1) Direct traversal
for key in Dictionary:
passfor key, value in dictionary items():
pass -
Add, modify - add key value pair
- DICTIONARY [key] = value. If the key exists, modify the value corresponding to the specified key; If the key does not exist, add a key value pair
- Dictionaries. SetDefault (key, value) add a key value pair (if the key does not exist, add a key value pair; if the key exists, do not move the dictionary)
-
Delete - delete key value pairs
del DICTIONARY [key] - delete the key value pair corresponding to the specified key
Dictionaries. Pop (key) - take out the value corresponding to the specified key -
Related operation
1) Operator: dictionary does not support: +, *, >, <, > =, < =, only = ==
2)in and not in - the in and not in operations of the dictionary determine whether the specified key exists in the dictionary
Key in dictionary3) Correlation function: len, dict
Len (Dictionary) - get the number of key value pairs in the dictionary
Dict (data) - converts the specified data into a dictionary
Requirements for data: 1 The data itself is a sequence
2. The elements in the sequence must be a small sequence with only two elements, and the first element is immutable data4) Related methods
a. Dictionary clear()
b. Dictionary copy()
c.
Dictionaries. keys() - returns a sequence in which the elements are all the keys of the dictionary
Dictionaries. values() - returns a sequence in which the elements are all the values of the dictionary
Dictionaries. items() - returns a sequence in which elements are tuples of keys and valuesd. update
Dictionaries. Update (sequence) - add all the elements in the sequence to the dictionary (the sequence must be a sequence that can be converted into a dictionary)
Dictionary 1 Update (dictionary 2) - add all key value pairs in dictionary 2 to dictionary 1
6. Dictionary derivation
{expression 1: expression 2 for variable in sequence}
{expression 1: expression 2 for variable in sequence if conditional statement}
task
-
Define a variable to save a student's information. Student confidence includes: name, age, grade (single subject), telephone and gender
dict1 = { 'name': 'Xiao Ming', 'age': 18, 'score': 66, 'tel': '15579927163', 'gender': 'male' }
-
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))
stu = [ {'name': 'Xiao Ming', 'age': 18, 'score': 100, 'tel': '132456', 'gender': 'male'}, {'name': 'floret', 'age': 25, 'score': 98, 'tel': '132874', 'gender': 'female'}, {'name': 'Zhang San', 'age': 34, 'score': 90, 'tel': '123428', 'gender': 'male'}, {'name': 'Li Si', 'age': 18, 'score': 70, 'tel': '947322', 'gender': 'Gender unknown'}, {'name': 'WangTwo ', 'age': 19, 'score': 55, 'tel': '346741', 'gender': 'male'}, {'name': 'Zhao Min', 'age': 18, 'score': 99, 'tel': '473669', 'gender': 'female'}, {'name': 'Lao Wang', 'age': 16, 'score': 43, 'tel': '132124', 'gender': 'male'} ] print(stu)
-
Count the number of failed students
count1 = 0 for i in stu: if i['score'] < 60: count1 += 1 print(count1)
-
Print the name of the failed minor student and the corresponding score
for i in stu: if i['score'] < 60 and i['age'] < 18: print(i['name'],i['score'])
-
Find the average age of all boys
otal_age = 0 for i in stu: total_age += i['age'] print(total_age/len(stu))
-
The student's name printed at the end of the mobile phone is 8
name1 = [i['name'] for i in stu if i['tel'][-1] == '8'] print(name1)
-
Print the highest score and the corresponding student's name
max_score = stu[0]['score'] max_name = [stu[0]['name']] for i in stu[1:]: if i['score'] > max_score: max_score = i['score'] max_name.clear() max_name.append(i['name']) elif i['score'] == max_score: max_name.append(i['name']) print(max_score, max_name)
-
Delete all students of Unknown Gender
for x in stu[:]: if x['gender'] == 'Gender unknown': stu.remove(x) print(stu)
-
Sort the list according to the students' grades from big to small (struggle, give up if you can't)
list1 =[stu[0]] for i in stu[1:]: for index, item in enumerate(list1): print(index, item) if i['score'] >= item['score']: list1.insert(index, i) break else: list1.append(i) print(list1)
-
-
Define a variable to save the information of a class. The class information includes: class name, classroom location, head teacher information, lecturer information and all students in the class (determine the data type and specific information according to the actual situation)
class1 = { 'class_name': 'python2201', 'address': '12 classroom', 'class_teacher': {'name': 'Rui Yan Zhang', 'gender': 'female', 'tel': '1221421'}, 'lecturer': {'name': 'Yu Ting', 'gender': 'female', 'tel': '13678192302'}, 'students': [ {'name': 'Xiao Ming', 'gender': 'male', 'age': 18, 'score': 100, 'education': 'specialty', 'linkman': {'name': 'Xiao Wu', 'tel': '110'}}, {'name': 'floret', 'gender': 'female', 'age': 20, 'score': 98, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Zhang', 'tel': '120'}}, {'name': 'Zhang San', 'gender': 'male', 'age': 30, 'score': 90, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Zhao', 'tel': '119'}}, {'name': 'Li Si', 'gender': 'male', 'age': 22, 'score': 70, 'education': 'specialty', 'linkman': {'name': 'Xiao Liu', 'tel': '134'}}, {'name': 'WangTwo ', 'gender': 'male', 'age': 28, 'score': 95, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Xu', 'tel': '2383'}}, {'name': 'Zhao Min', 'gender': 'female', 'age': 27, 'score': 99, 'education': 'specialty', 'linkman': {'name': 'Xiao Hu', 'tel': '23423'}}, {'name': 'Lao Wang', 'gender': 'male', 'age': 22, 'score': 89, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Wang', 'tel': '1234'}} ] }
-
It is known that a list stores dictionaries corresponding to multiple dogs:
dogs = [ {'name': 'Beibei', 'color': 'white', 'breed': 'Silver Fox', 'age': 3, 'gender': 'mother'}, {'name': 'tearful', 'color': 'grey', 'breed': 'FA Dou', 'age': 2}, {'name': 'Caicai', 'color': 'black', 'breed': 'Earth dog', 'age': 5, 'gender': 'common'}, {'name': 'steamed stuffed bun', 'color': 'yellow', 'breed': 'Siberian Husky', 'age': 1}, {'name': 'cola', 'color': 'white', 'breed': 'Silver Fox', 'age': 2}, {'name': 'Wangcai', 'color': 'yellow', 'breed': 'Earth dog', 'age': 2, 'gender': 'mother'} ]
-
Use the list derivation to obtain the breeds of all dogs
['silver fox', 'fadou', 'earth dog', 'husky', 'silver fox', 'earth dog']
breed1 = [dog['breed'] for dog in dogs] print(breed1)
-
Use list derivation to get the names of all white dogs
['Beibei', 'Coke']
name1 = [dog['name'] for dog in dogs if dog['color'] == 'white'] print(name1)
-
Add "male" to dogs without gender in dogs
for dog in dogs: dog.setdefault('gender', 'common') print(dogs)
-
Count the number of 'silver foxes'
count1 = len([dog for dog in dogs if dog['breed'] == 'Silver Fox']) print(count1)
-