day8 dictionary
I Cognitive dictionary
-
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
-
Cognitive Dictionary (dict)
""" 1) Is a container data type; take{}As the flag of the container, multiple key value pairs are separated by commas: {Key 1: Value 1, Key 2: Value 2, Key 3: Value 3,...} Format of key value pairs: key:value 2) characteristic Dictionaries are variable(Support addition, deletion and modification); Dictionaries are 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: Keys must be immutable types of data(Numbers, strings, Booleans, tuples, etc);Key is unique b. Value requirements: No requirement """ # Empty dictionary dict1 = {} # Elements in a dictionary can only be key value pairs dict2 = {'name': 'Xiao Ming', 'age': 20} print(dict2) # dict3 = {'name': 'Zhang San', 30} # report errors! 30 is not a key value pair # Dictionary disorder print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) # True # Keys are immutable types of data dict3 = {10: 23, 1.23: 10, 'abc': 30, (1, 2): 50} print(dict3) # dict4 = {10: 23, 1.23: 10, 'abc': 30, [1, 2]: 50} # report errors! # Key is unique dict4 = {'a': 10, 'b': 20, 'c': 30, 'a': 100} print(dict4) # {'a': 100, 'b': 20, 'c': 30}
II Basic operation of dictionary
-
Look up - gets the value of the dictionary
Check single (important) - get one value at a time
""" Grammar 1: Dictionary[key] - Gets 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) - Gets the value corresponding to the specified 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 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': 'Chinese pastoral dog', 'color': 'white'} print(dog['age']) print(dog['name']) # print(dog['weight']) # report errors! KeyError: 'weight' print(dog.get('breed')) print(dog.get('color')) print(dog.get('weight')) # None print(dog.get('weight', 5)) # 5
-
The correct way to open lists and dictionaries
# 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': 100, '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 # teacher = class1['lecturer'] # print(teacher['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 all_student = class1['students'] count = 0 for stu in all_student: if stu['gender'] == 'male': count += 1 print('Number of boys:', count) # 5) Calculate the average score of all students # Method 1: # total_score = 0 # for stu in all_student: # total_score += stu['score'] # print('average score: ', total_score / len(all_student)) # Method 2: result = sum([stu['score'] for stu in all_student]) / len(all_student) print('average:', result) # 6) Get the name of the student with the highest score # Method 1: get the highest score first, and then see who has the same score as 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 max_score = all_student[0]['score'] names = [all_student[0]['name']] for stu in all_student[1:]: score = stu['score'] if score > max_score: max_score = score names.clear() names.append(stu['name']) elif score == max_score: names.append(stu['name']) print(max_score, names) # 7) Get the phone number of all emergency contacts for stu in all_student: print(stu['linkman']['tel'])
-
ergodic
""" 1) 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]) print('------------------------') for key, value in stu.items(): print(key, value) print(stu.items()) for x in stu.items(): print(x)
III Dictionary addition, deletion and modification
-
Add / modify - add key value pair
""" 1) Dictionaries[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 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) """
Example:
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', 1000) print(cat) # {'name': 'Xiaobai', 'feed': 'Garfield', 'color': 'white', 'age': 2, 'price': 1000}
Exercise: add a discount value of 1 to items without discount
all_goods = [ {'name': 'Instant noodles', 'price': 3.5, 'count': 1723, 'discount': 0.5}, {'name': 'mineral water', 'price': 2, 'count': 91723}, {'name': 'bread', 'price': 5, 'count': 290}, {'name': 'Ham sausage', 'price': 1, 'count': 923, 'discount': 0.95} ] for x in all_goods: x.setdefault('discount', 1) print(all_goods)
-
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': 'Xiaobai', 'breed': 'Garfield', 'color': 'white', 'age': 2, 'price': 1000} del cat['breed'] print(cat) # {'name': 'little white', 'color': 'white', 'age': 2, 'price': 1000} result = cat.pop('color') print(cat, result) # {'name': 'little white', 'age': 2, 'price': 1000} white
IV Dictionary related operation functions and methods
-
Related operation
-
Operator: dictionary does not support +, *, >, <, > =, < =, only = ==
-
In and not in - the in and not in operations of the dictionary determine whether the specified key exists in the dictionary
# Key in dictionary dict1 = {'a': 10, 'b': 20, 'c': 30} print(10 in dict1) # False print('a' in dict1) # True
-
-
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)) # {'a': 'b', 'c': 'd', 'e': 'f'} seq = [(10, 20), range(2), 'he'] print(dict(seq)) # {10: 20, 0: 1, 'h': 'e'}
-
correlation method
-
Dictionaries. clear()
-
Dictionaries. copy()
-
Dictionaries. keys()
-
Dictionaries. values()
-
Dictionaries. items()
dog = {'name': 'chinese rhubarb', 'breed': 'Earth dog', 'gender': 'Bitch'} 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 ')])
-
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)
-
-
V 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 the information of a student. The student information includes: name, age, grade (single subject), telephone and gender
student = { 'name':'Topku ' , 'age': 23, 'score': 100, 'tel': '18782667516', 'gender':'male' } print(student)
-
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))
-
Count the number of failed students
-
Print the name of the failed minor student and the corresponding score
-
Find the average age of all boys
-
The student's name printed at the end of the mobile phone is 8
-
Print the highest score and the corresponding student's name
-
Delete all students of Unknown Gender
-
Sort the list according to the students' grades from big to small (struggle, give up if you can't)
students = [ {'name':'Topku ' ,'age': 23,'score': 90,'tel': '187826','gender':'male'}, {'name':'Sun Xiang' ,'age': 22,'score': 100,'tel': '17378','gender':'female'}, {'name':'Qin Xiangyi' ,'age': 24,'score': 80,'tel': '13408','gender':'female'}, {'name':'Qin Jiayi' ,'age': 16,'score': 50,'tel': '110','gender':'female'}, {'name':'Qin Wenyi' ,'age': 29,'score': 78,'tel': '120','gender':'female'}, {'name':'He Hailong' ,'age': 28,'score': 56,'tel': '119','gender':'Unknown'} ] # 1 count = 0 for i in students: if i['score'] < 60: count += 1 print(count) # 2 for i in students: if i['score'] < 60 and i['age'] < 18: print(i['name'],i['score']) # 3 result = [i['age'] for i in students if i['gender'] == 'male'] print(sum(result) / len(result)) # 4 result = [i['name'] for i in students if i['tel'][-1] == '8'] print(result) # 5 max_score = students[0]['score'] names = [students[0]['name']] for i in students: score = i['score'] if score > max_score: max_score = score names.clear() names.append(i['name']) elif score == max_score: names.append(i['name']) print(max_score,names) # 6 for i in range(len(students)): if students[i]['gender'] == 'Unknown': del students[i] print(students) # 7 score = [x['score'] for x in students] new_list = sorted(score,reverse=True) scores = [] for i in students: for j in range(len(new_list)): if new_list[j] == i['score']: scores.insert(j,i) print(scores)
-
-
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', 'adress':'12 classroom', 'class_teacher':{ 'name':'Rui Yan Zhang', 'gender':'female', 'age':'18', 'tel':'1623456' }, 'lecturer':{ 'name':'Yu Ting', 'gender':'female', 'age':'18', 'tel':'1623456' }, 'students':[ {'name': 'Topku ', 'age': 23, 'score': 90, 'tel': '18782667516', 'gender': 'male'}, {'name': 'Tian Wei', 'age': 22, 'score': 100, 'tel': '17378589778', 'gender': 'male'}, {'name': 'Wang Yuxuan', 'age': 24, 'score': 80, 'tel': '13408261924', 'gender': 'male'}, {'name': 'Chen Xiang', 'age': 16, 'score': 50, 'tel': '11023155622', 'gender': 'male'}, {'name': 'He Zhouyang', 'age': 25, 'score': 78, 'tel': '12136568128', 'gender': 'male'}, {'name': 'Dai Xinrui', 'age': 22, 'score': 100, 'tel': '11921343545', 'gender': 'female'} ] } print(class1)
-
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']
result = [i['breed'] for i in dogs] print(result)
-
Use list derivation to get the names of all white dogs
['Beibei', 'Coke']
result = [i['name'] for i in dogs if i['color'] == 'white'] print(result
-
Add "male" to dogs without gender in dogs
for i in dogs: i.setdefault('gender','common') print(dogs)
-
Count the number of 'silver foxes'
count = 0 for i in dogs: if i['breed'] == 'Silver Fox': count += 1 print(count)
-