3.2 dictionary
1. If there is no dictionary
1) Define a variable to save the information of a student
# Use list stu1 = ['Xiao Ming',28,'male',170,63,80,89,99] print(stu1[0],stu1[-1]) #Xiaoming 99 # Use dictionary stu2 ={'name':'Xiao Ming','age':28,'Gender':'male','height':170,'weight':63,'language':80,'mathematics':89,'English':99} print(stu2['name'],stu2['English']) #Xiaoming 99
2) Selection of dictionaries and lists
If multiple data with the same meaning (all names, ages, students, etc.) are saved at the same time, use the list;
If you save multiple data with different meanings at the same time, use a dictionary.
2. What is a dictionary (dict)
1) The dictionary is a container data type. It takes {} as the flag of the container, and multiple key value pairs are separated by commas: {key 1: value 1, key 2: value 2, key 3: value 3...}
2) The dictionary is changeable (it supports addition, deletion and modification); Dictionary is unnecessary (subscript operation is not supported)
3) Dictionary requirements: the elements of the dictionary are key value pairs
Key requirements: a The key must be data of immutable type (generally using string) b. the key is unique
Value requirements: no requirements
# Empty dictionary dict1 = {} print(len(dict1),type(dict1)) #0 <class 'dict'>
3. The dictionary is out of order
print({'a':10,'b':20} == {'b':20,'a':10}) #True
The key must be data of immutable type (string, Boolean, null value, number, tuple)
dict2 = {10:20,'ab':30,(10,20):40} print(dict2) #{10: 20, 'ab': 30, (10, 20): 40} # dict2 = {10:20,'ab':30,[10,20]:40} # print(dict2) # unhashable type: 'list'
Key is unique
dict3 = {'a':100,'b':20,'a':30} print(dict3) #{'a': 30, 'b': 20}
3.2.1 dictionary lookup
1. Look up single - get the value corresponding to a key in the dictionary
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
2) Dictionary 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) - get the value corresponding to the specified 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': 'Earth dog', 'gender': 'Bitch'} print(dog['name'], dog['gender']) #Wangcai bitch print(dog.get('name'), dog.get('age')) #Wangcai 3 # print(dog['color']) # KeyError: 'color' print(dog.get('color')) # None print(dog.get('color', 'white')) # White (if it does not exist, the default value is returned)
3) Dictionary in real life
Define a variable to save the information of a class: class name, location, lecturer, head teacher, and all students
class1 = { 'class_name': 'Python2204', 'address': '15 teach', 'lecturer': {'name': 'Yu Ting', 'age': 18, 'qq': '726550822', 'gender': 'female'}, 'class_teacher': {'name': 'Quiet', 'tel': '110'}, 'students': [ {'name': 'stu1', 'age': 21, 'major': 'accounting', 'tel': '120', 'contacts': {'name': 'Zhang San', 'tel': '162723'}}, {'name': 'stu2', 'age': 30, 'major': 'Electronics', 'tel': '219223', 'contacts': {'name': 'Xiao Ming', 'tel': '281912'}}, {'name': 'stu3', 'age': 19, 'major': 'tourism management', 'tel': '123233', 'contacts': {'name': 'floret', 'tel': '886552'}}, {'name': 'stu4', 'age': 25, 'major': 'signal communication', 'tel': '4444221', 'contacts': {'name': 'Li Si', 'tel': '22342345'}}, {'name': 'stu5', 'age': 25, 'major': 'Mechanics', 'tel': '223111', 'contacts': {'name': 'Wang Wu', 'tel': '555632'}}, {'name': 'stu6', 'age': 23, 'major': 'mathematics', 'tel': '234234', 'contacts': {'name': 'Zhao Liu', 'tel': '96533'}} ] } # 1) Print class name and classroom print(class1['class_name'], class1['address']) #Python2204 15 teach # 2) Print the name and age of the class instructor lecturer = class1['lecturer'] print(lecturer['name'], lecturer['age']) #Yu Ting 18 # print(class1['lecturer']['name']) # {'name': 'Yu Ting','age': 18,'qq':'726550822','gender': 'female'}['name'] # 3) Print the phone number of the head teacher print(class1['class_teacher']['tel']) #110 # 4) Print the names of all students # Method 1: all_student = class1['students'] for stu in all_student: print(stu['name']) # Method 2: # ['stu1', 'stu2', ..., 'stu6'] result = [x['name'] for x in class1['students']] print(result) #['stu1', 'stu2', 'stu3', 'stu4', 'stu5', 'stu6'] # 5) Calculate the average age of all students # Method 1: all_student = class1['students'] total_age = stu_count = 0 for stu in all_student: total_age += stu['age'] stu_count += 1 print('average age:', total_age / stu_count) #Average age: 23.833333333333332 # Method 2 print('average age:', sum([x['age'] for x in class1['students']]) / len(class1['students'])) # 6) Print the names of all students' contacts # Method 1: all_student = class1['students'] for x in all_student: print(x['contacts']['name']) # Method 2: result = [x['contacts']['name'] for x in class1['students']] print(result) # 7) Print the names of students whose phone numbers of all contacts end with 2 # ['stu2', 'stu3', 'stu5'] # Method 1: result = [x['name'] for x in class1['students'] if x['contacts']['tel'][-1] == '2'] print(result) # Method 2: for stu in class1['students']: if stu['contacts']['tel'][-1] == '2': print(stu['name'])
2. Traverse the dictionary
Method 1:
for key in Dictionary:
Loop body (to yes key obtained by variable)
Method 2:
for key, value in dictionary.items():
Circulatory body
dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Earth dog', 'gender': 'Bitch'} for x in dog: print('x:', x, dog[x]) for key, value in dog.items(): print(key, value)
3.2.2 addition, deletion and modification of dictionary
- Change - modify the value corresponding to a key
DICTIONARY [key] = new value - modify the value corresponding to the specified key in the dictionary to the specified new value
dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Earth dog', 'gender': 'Bitch'} print(dog) # {'name': 'Wangcai', 'age': 3,'breed':' hyena ',' gender':' bitch '} dog['name'] = 'Caicai' print(dog) # {'name': 'Caicai', 'age': 3,'breed':' hyena ',' gender':' bitch '}
- Add - add key value pairs
1) DICTIONARY [key] = value - if the key does not exist, add a key value pair to the dictionary; If the key exists, the value of the key value pair will be modified
2) Dictionary SetDefault (key, value) - add the specified key value pair to the dictionary; If the key exists, the original value will be retained (it will not be modified)
dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Earth dog', 'gender': 'Bitch'} print(dog) # {'name': 'Wangcai', 'age': 3,'breed':' hyena ',' gender':' bitch '} dog['color'] = 'yellow' print(dog) # {'name': 'Wangcai', 'age': 3,'breed':' hyena ',' gender':' bitch ',' color':' yellow '} dog.setdefault('weight', 15) print(dog) # {'name': 'Wangcai', 'age': 3,'breed':' hyena ',' gender':' bitch ',' color':' yellow ',' weight': 15} # The existence of the key will modify the value of the key value pair dog['age'] = 10 print(dog) # {'name': 'Wangcai', 'age': 10,'breed':' hyena ',' gender':' bitch ',' color':' yellow ',' weight': 15} # If the key exists, the original value will be retained (it will not be modified) dog.setdefault('gender', 'male dog') print(dog) goods_list = [ {'name': 'Instant noodles', 'price': 4, 'discount': 0.9}, {'name': 'Ham sausage', 'price': 1.5}, {'name': 'mineral water', 'price': 2, 'discount': 0.8}, {'name': 'bread', 'price': 5.5}, {'name': 'Yogurt', 'price': 7.5} ] # Add a discount value of 1 to products without discount for goods in goods_list: goods.setdefault('discount', 1) print(goods_list)
- Delete - delete key value pairs
1) del DICTIONARY [key] - delete the key value pair corresponding to the specified key in the dictionary
2) Dictionary Pop (key) - take out the value corresponding to the specified key in the dictionary
dog = {'name': 'Wangcai', 'age': 10, 'breed': 'Earth dog', 'gender': 'Bitch', 'color': 'yellow', 'weight': 15} print(dog) # {'name': 'Wangcai', 'age': 10,'breed':' hyena ',' gender':' bitch ',' color':' yellow ',' weight': 15} del dog['gender'] print(dog) # {'name': 'Wangcai', 'age': 10,'breed':' hyena ',' color':' yellow ',' weight': 15} color = dog.pop('color') print(dog, color) # {'name': 'Wangcai', 'age': 10,'breed':' hyena ',' weight': 15}
3.2.3 relevant operations
Dictionary does not support +, *, >, <, > =<=
- In and not in - determine whether the specified key exists or does not exist in the dictionary
Key in dictionary
Key not in dictionary
dict1 = {'a': 10, 'b': 20, 'c': 30} print(10 in dict1) # False print('b' in dict1) # True
2. Correlation function: len, dict
1) Len (Dictionary) - get the number of key value pairs in the dictionary
2) Dict (data) - converts the specified data into a dictionary
Requirements for data that can be converted into Dictionaries:
a. The data itself is a sequence
b. The element in the sequence must be a small sequence with only two elements
c. The first element of a small sequence must be data of immutable type
result = dict(['ab', 'cd', 'ef']) print(result) # {'a': 'b', 'c': 'd', 'e': 'f'} result = dict([('name', 'xiaoming'), ('age', 18)]) print(result) # {'name': 'xiaoming', 'age': 18}
Note: when the dictionary is converted into a list, all the keys of the dictionary are taken as the elements of the list
dog = {'name': 'Wangcai', 'age': 10, 'breed': 'Earth dog', 'gender': 'Bitch', 'color': 'yellow', 'weight': 15} print(list(dog)) # ['name', 'age', 'breed', 'gender', 'color', 'weight']
3. Related methods: dictionary.xxx()
1) Dictionary clear() - clear the dictionary
2) Dictionary copy() - copy the dictionary to produce an identical new dictionary
3) Dictionary 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
Dictionaries. items() - convert the dictionary into a sequence, and convert each key value pair into a tuple
dog = {'name': 'Wangcai', 'age': 10, 'breed': 'Earth dog', 'gender': 'Bitch', 'color': 'yellow', 'weight': 15} print(dog.keys()) #dict_keys(['name', 'age', 'breed', 'gender', 'color', 'weight']) print(dog.values()) #dict_values(['Wangcai', 10, 'local dog', 'bitch', 'yellow', 15]) print(dog.items()) #dict_items([('name',' Wangcai '), ('age', 10), ('breed',' hyena '), ('gender', 'bitch'), ('color',' yellow '), ('weight', 15)])
4) Dictionary 1.update (dictionary 2) - add all key value pairs in dictionary 2 to dictionary 1
d1 = {'a': 10, 'b': 20} d2 = {'x': 100, 'y': 200} d1.update(d2) print(d1) # {'a': 10, 'b': 20, 'x': 100, 'y': 200}
Homework today
-
Define a variable to store a student's information. Student confidence includes: name, age, grade (single subject), phone number, and gender
stu1 = {'name':'Zhang San','age':21,'score_Chinese':90,'score_math':100,'score_English':99,'tel':110,'gender':'male'} print(stu1)
-
Define a list, and save the information of 6 students in the list (student information includes: name, age, grade (single subject), phone number, gender (male, female, unknown))
(1) Count the number of failed students
(2) Print the names and corresponding grades of the underage students who failed
# Method 1: for i in list1: if i['score'] < 60: print(i['name'],i['score']) # Method 2: list2=[(i['name'],i['score']) for i in list1 if i['score'] < 60] print(list2)
(3) Average age of all boys
count = 0 sum = 0 for i in list1: if i['gender'] == 'male': count +=1 sum += i['age'] print(sum/count)
(4) Print the name of the student whose mobile phone tail number is 8
name1=[i['name'] for i in list1 if i['tel'] % 10 == 8] print(name1)
(5) Print the highest score and the name of the corresponding student
list3=[] for i in list1: list3.append(i['score']) list3.sort() if i['score'] == list3[-1]: print(i['score'],i['name'])
(6) Delete all students of Unknown Gender
list4=[list1[i] for i in range(len(list1)) if list1[i]['gender'] != 'Unknown'] print(list4)
(7) Sort the list from big to small according to students' grades (struggle, give up if you can't)
for i in range(1,len(list4)): for j in range(0,len(list4)-i): if list4[j]['score'] > list4[j+1]['score']: list4[j]['score'],list4[j+1]['score']=list4[j+1]['score'],list4[j]['score'] print(list4)
-
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':'python2204', 'class_location':'15classroom', 'class_teacher':{'name':'Sister Jing','gender':'female','position':'unknown','tel':234567890,'QQ':234523,'WX':1563214}, 'lecturer':[{'name': 'Sister Ting','gender':'female','position':'lecturer','tel':15632452,'QQ':563255,'WX':56321563}, {'name': 'Brother Fu','gender':'male','position':'lecturer','tel':14523422,'QQ':63252452,'WX':523563}], 'students': [ {'name': 'stu1', 'age': 21,'gender':'male', 'major': 'accounting', 'tel': '120', 'contacts': {'name': 'Zhang San', 'tel': '162723'}}, {'name': 'stu2', 'age': 26,'gender':'female', 'major': 'Electronics', 'tel': '219223', 'contacts': {'name': 'Xiao Ming', 'tel': '281912'}}, {'name': 'stu3', 'age': 19,'gender':'male', 'major': 'tourism management', 'tel': '123233', 'contacts': {'name': 'floret', 'tel': '886552'}}, {'name': 'stu4', 'age': 22,'gender':'female', 'major': 'signal communication', 'tel': '4444221', 'contacts': {'name': 'Li Si', 'tel': '22342345'}}, {'name': 'stu5', 'age': 21,'gender':'male', 'major': 'Mechanics', 'tel': '223111', 'contacts': {'name': 'Wang Wu', 'tel': '555632'}}, {'name': 'stu6', 'age': 230,'gender':'female', 'major': 'mathematics', 'tel': '234234', 'contacts': {'name': 'Zhao Liu', 'tel': '96533'}} ] }
-
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': 'Fadou', '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'} ]
(1) Use the list derivation to obtain the breeds of all dogs
['silver fox', 'fadou', 'local dog', 'husky', 'silver fox', 'local dog']
dog_breed = [i['breed'] for i in dogs] print(dog_breed)
(2) Use list derivation to get the names of all white dogs
['Beibei', 'Cola']
white_dog_name = [i['name'] for i in dogs if i['color'] == 'white'] print(white_dog_name)
(3) Add gender 'male' to dogs without gender in dogs
for i in dogs: i.setdefault('gender','common') print(dogs)
(4) Count the number of 'silver foxes'
count = 0 for i in dogs: if i['breed'] == 'Silver Fox': count += 1 print(count)