day8 dictionary
1. Recognize the dictionary
1. Dictionary and list selection:
When you need to save multiple data at the same time, use the list if the meaning of multiple data is the same (there is no need to distinguish); If multiple data have different meanings, use a dictionary
2. Cognitive Dictionary (dict)
1) 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,...}
Format of key value pair: key value
2) Characteristics
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)
3) Requirements for elements
Dictionary elements are key value pairs
a. Key requirements: the key must be immutable type of data (number, string, Boolean, tuple, etc.); Key is unique
b. Value requirement: no requirement
2. Basic operation of dictionary
1. Look up - get the value of the dictionary
Check single (important) - get one value at a time
""" Grammar 1:Dictionaries[key] - Obtain the value corresponding to the pointing key in the dictionary; No key error Grammar 2: Dictionaries.get(key) - Gets the value corresponding to the pointing key in the dictionary;If the key does not exist, no error will be reported, and return None Dictionaries.get(key, Default value) - Gets the value corresponding to the pointing key in the dictionary;If the key does not exist, no error will be reported, and the default value will be returned """
dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Chinese pastoral dog', 'color': 'white'} print(dog['age']) print(dog['name']) # print(dog['weight']) # KeyError: 'weight' print(dog.get('breed')) print(dog.get('color')) # print(dog.get('weight')) # None print(dog.get('weight', 5)) # 5
2. Correct opening method of list and dictionary
Define a variable to save the information of a class
class1 = { 'name': 'python2201', 'address': '12 classroom', 'lecturer': { 'name': 'Yu Ting', 'gender': 'female', 'tel': '13678192302' }, 'class_teacher': { 'name': 'Rui Yan Zhang', 'gender': 'female', 'tel': '110', 'age': 20, 'QQ': '617818271' }, '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'}} ] } # 1) Get class name print(class1['name']) # 2) Get the instructor's name print(class1['lecturer']['name']) # 3) Get the phone number of the head teacher print(class1['class_teacher']['tel']) # 4) Count the number of boys among students count = 0 for x in class1.get('students'): if x['gender'] == 'male': count += 1 print(count) # 5) Calculate the average score of all students # Method 1 avg = 0 count = 0 for x in class1['students']: avg += x['score'] count += 1 print(avg / count) # Method 2 all_student = class1['students'] result = sum(stu['score'] for stu in all_student) / len(all_student) print(result) # 6) Get the name of the student with the highest score # Method 1: # Get the highest score first, and then see whose score is equal to the highest score max_score = max(stu['score'] for stu in all_student) names = [stu['name'] for stu in all_student if stu['score'] == max_score] print(names) # Method 2: # Suppose the first student has the highest score all = class1['students'] max_sc = all[0]['score'] names = [all[0]['name']] for stu in all[1:]: score = stu['score'] if score > max_sc: max_sc =score names.clear() names.append(stu['name']) elif score == max_sc: names.append(stu['name']) print(max_sc, names) # 7) Get the phone number of all emergency contacts nums = [] for x in class1.get('students'): nums.append(x.get('linkman')['tel']) print(nums)
3. Traversal
""" 1)Direct traversal for key in Dictionaries: pass 2) for key,value in Dictionaries.items(): pass """
stu = {'name': 'Xiao Ming', 'gender': 'male', 'age': 18, 'score': 100, 'education': 'specialty'} for x in stu: print(x, stu[x]) for key, value in stu.items(): print(key, value)
3. Addition, deletion and modification of dictionary
1. Add / modify - add key value pair
""" 1)Dictionaries[key] = value If the key exists, modify the specified value;If the key does not exist, add a key value pair 2)Dictionaries.setdefault(key, value) Add key value pair(If the key does not exist, the key value pair is added. If the key exists, the fixed dictionary is added) """
cat = {'name': 'tearful', 'breed': 'Garfield', 'color': 'white'} print(cat) # modify cat['name'] = 'Xiaobai' print(cat) # {'name': 'Xiaobai', 'feed': 'Garfield', 'color': 'white'} # add to cat['age'] = 2 print(cat) # {'name': 'Xiaobai', 'feed': 'Garfield', 'color': 'white', 'age': 2} # Add 2 cat.setdefault('price', 2000) print(cat) # {'name': 'Xiaobai', 'feed': 'Garfield', 'color': 'white', 'age': 2, 'price': 2000}
2. Delete - delete key value pairs
""" del Dictionaries[key] - Delete the key value pair corresponding to the specified key Dictionaries.pop(key) - Take out the value corresponding to the specified key """
cat = {'name': 'tearful', 'breed': 'Garfield', 'color': 'white'} del cat['breed'] print(cat) result = cat.pop('color') print(cat, result) # {'name': 'Huahua'} white
4. Dictionary related operation functions and methods
1. Related operations
1.Dictionary not supported: +,*,>,<,>=,<=,Only support: == ,!= 2.in and not in - Dictionary in and not in The operation determines whether the specified key exists in the dictionary key in Dictionaries dict1 = {'a': 10, 'b': 20, 'c': 30} print(10 in dict1) # False print('a' in dict1) # True 3.correlation function:len,dict """ a. len(Dictionaries) - Gets the number of key value pairs in the dictionary b. 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 data """ print(len(dict1)) seq = ['ab', 'cd', 'ef'] print(dict(seq)) 4.correlation method # a. Dictionary clear() # b. Dictionary copy() dog = {'name': 'chinese rhubarb', 'breed': 'Earth dog', 'gender': 'Bitch'} dog1 = dog dog2 = dog.copy() print(dog1, dog2) # c. # Dictionaries. keys() - returns a sequence in which the elements are all the keys of the dictionary # Dictionaries. value() - returns a sequence in which the elements are all the values of the dictionary # Dictionaries. items() - returns a sequence in which the elements are tuples consisting of each pair of keys and values print(dog.keys()) # dict_keys(['name', 'breed', 'gender']) print(dog.values()) # dict_values(['Caicai', 'local dog', 'bitch']) print(dog.items()) # dict_items([('name ',' Caicai '), ('bread', 'earth dog'), ('gender ',' bitch ')]) # d.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 dict1 = {'a': 10, 'b': 20} dict2 = {'c': 100, 'd': 200, 'a': 1000} dict1.update(dict2) print(dict1)
5. Dictionary derivation
Dictionary derivation
"""
{expression 1: expression 2 for variable in sequence}
{expression 1: expression 2 for variable in sequence if conditional statement}
"""
result = {x: x*2 for x in range(5)} print(result) result = {x: x for x in range(10) if x % 3} print(result)
task
-
Define a variable to save a student's information. Student confidence includes: name, age, grade (single subject), telephone and gender
dict1 = {'name': 'lth', 'age': 18, 'score': '98', 'tel': '18944545', '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))
students = [ {'name': 'Xiao Ming', 'age': 18, 'score': 100, 'tel': '110428228', 'gender': 'male'}, {'name': 'floret', 'age': 20, 'score': 43, 'tel': '1208282748', 'gender': 'female'}, {'name': 'Zhang San', 'age': 30, 'score': 90, 'tel': '1324534340', 'gender': 'Unknown'}, {'name': 'Li Si', 'age': 22, 'score': 56, 'tel': '1405445448', 'gender': 'Unknown'}, {'name': 'WangTwo ', 'age': 28, 'score': 95, 'tel': '1542453440', 'gender': 'Unknown'}, {'name': 'Zhao Min', 'age': 27, 'score': 100, 'tel': '1603435343', 'gender': 'female'}, ]
-
Count the number of failed students
count = 0 for x in students: if x['score'] < 60: count += 1 print(count)
-
Print the name of the failed minor student and the corresponding score
for x in students: if x['score'] < 60 and x['age'] < 18: print(x['score'],x['name'])
-
Find the average age of all boys
sum = 0 count = 0 for x in students: if x['gender'] == 'male': sum += x['score'] count += 1 result = sum / count print(result)
-
The student's name printed at the end of the mobile phone is 8
print([x['name'] for x in students if x['tel'][-1] == '8'])
-
Print the highest score and the corresponding student's name
max_score = max(stu['score'] for stu in students) for x in students: if x['score'] == max_score: print(x['score'], x['name'])
-
Delete all students of Unknown Gender
x = 0 while x < len(students): if students[x]['gender'] == 'Unknown': students.remove(students[x]) else: x += 1 print(students)
-
Sort the list according to the students' grades from big to small (struggle, give up if you can't)
-
-
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 = { 'name': 'python2201', 'address': '12 classroom', 'lecturer': { 'name': 'Yu Ting', 'gender': 'female', 'tel': '13678192302' }, 'class_teacher': { 'name': 'Rui Yan Zhang', 'gender': 'female', 'tel': '110', 'age': 20, 'QQ': '617818271' }, 'students': [ {'name': 'Xiao Ming', 'gender': 'male', 'age': 18, 'score': 100, 'education': 'specialty'}, {'name': 'floret', 'gender': 'female', 'age': 20, 'score': 98, 'education': 'undergraduate'}, {'name': 'Zhang San', 'gender': 'male', 'age': 30, 'score': 90, 'education': 'undergraduate'}, {'name': 'Li Si', 'gender': 'male', 'age': 22, 'score': 70, 'education': 'specialty'}, {'name': 'WangTwo ', 'gender': 'male', 'age': 28, 'score': 95, 'education': 'undergraduate'}, {'name': 'Zhao Min', 'gender': 'female', 'age': 27, 'score': 99, 'education': 'specialty'}, {'name': 'Lao Wang', 'gender': 'male', 'age': 22, 'score': 89, 'education': 'undergraduate'} ] }
-
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']
print([x['breed'] for x in dogs])
-
Use list derivation to get the names of all white dogs
['Beibei', 'Coke']
print([x['name'] for x in fogs if x['color'] == 'white'])
-
Add "male" to dogs without gender in dogs
for x in dogs: x.setdefault('gender', 'common') print(dogs)
-
Count the number of 'silver foxes'
count = 0 for x in dogs: if x['breed'] == 'Silver Fox': count += 1 print(count)
-