day8 dictionary summary and homework

day8 dictionary summary and homework

1, Cognitive 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

  1. 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,...}

Format of key value pair: key value

dict1 = {}   # Empty dictionary

Elements in a dictionary can only be key value pairs

dict2 = {'name': 'Xiao Ming', 'age': 20}
dict3 = {'name': 'Zhang San', 30}        # report errors! 30 is not a key value pair

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)

print({'a': 10, 'b': 20} == {'b': 20, 'a': 10})         # True

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

dict4 = {'a': 10, 'b': 20, 'c': 30, 'a': 100}
print(dict4)        # {'a': 100, 'b': 20, 'c': 30}

2, Basic operation of dictionary

  1. Look up - gets the value of the dictionary

1) Look up a single - 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

dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Chinese pastoral dog', 'color': 'white'}
print(dog['name'])     # Wangcai
print(dog['weight'])      # report errors! KeyError: 'weight'

Grammar 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

dog = {'name': 'Wangcai', 'age': 3, 'breed': 'Chinese pastoral dog', 'color': 'white'}
print(dog.get('color'))        #white
print(dog.get('weight'))        # None

Grammar 3: dictionary Get (key, default value) - 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': 'Chinese pastoral dog', 'color': 'white'}
print(dog.get('weight', 5))   # 5

2) Traversal

for  key  in  Dictionaries:
	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 Dictionaries.item():
	pass
stu = {'name': 'Xiao Ming', 'gender': 'male', 'age': 18, 'score': 100, 'education': 'specialty'}
for key, value in stu.items():
    print(key, value)

3, Dictionary addition, deletion and modification

  1. Add / modify - add key value pair

1) DICTIONARY [key] = value. If the key exists, modify the value corresponding to the specified key; If it does not exist, add a key value pair

cat = {'name': 'tearful', 'breed': 'Garfield', 'color': 'white'}
#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}

2) Dictionary 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)

cat = {'name': 'Xiaobai', 'breed': 'Garfield', 'color': 'white', 'age': 2}
cat.setdefault('price', 1000)
print(cat)      # {'name': 'Xiaobai', 'feed': 'Garfield', 'color': 'white', 'age': 2, 'price': 1000}
  1. Delete - delete key value pairs

1) del DICTIONARY [key] - delete the key value pair 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}

2) Dictionary Pop (key) - take out the value corresponding to the specified key

cat = {'name': 'Xiaobai', 'color': 'white', 'age': 2, 'price': 1000}
result = cat.pop('color')
print(cat, result)      # {'name': 'little white', 'age': 2, 'price': 1000} white

4, Dictionary related operation functions and methods

  1. Related operation

1) Dictionary does not support: +, *, >, <, > =, < =, only: = ==

2) Determine whether the in and not keys in the dictionary exist

Key in dictionary

dict1 = {'a': 10, 'b': 20, 'c': 30}
print(10 in dict1)      # False
print('a' in dict1)     # True
  1. Correlation function: len, dict

1) Len (Dictionary) - get the number of key value pairs in the dictionary

dict1 = {'a': 10, 'b': 20, 'c': 30}
print(len(dict1))    #3

2) Dict (data) - converts the specified data into a dictionary

Requirements for data:

  • The data itself is a sequence

  • The and elements in the sequence must be a small sequence with only two elements, and the first element is immutable data

seq = [(10, 20), range(2), 'he']
print(dict(seq))        # {10: 20, 0: 1, 'h': 'e'}
  1. correlation method

1) Dictionary clear()

2) Dictionary copy()

3)

a. Dictionary keys() - returns a sequence in which the elements are all the keys of the dictionary

b. Dictionary values() - returns a sequence in which the elements are all the values of the dictionary

c. Dictionary items() - returns a sequence in which the elements are composed of each pair of keys and values

dog = {'name': 'chinese rhubarb', 'breed': 'Earth dog', 'gender': 'Bitch'}
print(dog.keys())       # dict_keys(['name', 'breed', 'gender'])
print(dog.values())     # dict_values(['rhubarb', 'earth dog', 'bitch'])
print(dog.items())      # dict_items([('name ',' rhubarb '), ('bread', 'earth dog'), ('gender ',' bitch ')])

4)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)    #{'a': 1000, 'b': 20, 'c': 100, 'd': 200}

5, Dictionary derivation

  1. Dictionary derivation

{expression 1: expression 2 for variable in sequence}

result = {x: x*2 for x in range(5)}
print(result)   #{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

{expression 1: expression 2 for variable in sequence if conditional statement}

result = {x: x for x in range(10) if x % 3}
print(result)    #{1: 1, 2: 2, 4: 4, 5: 5, 7: 7, 8: 8}

task

1. Define a variable to save a student's information. Student confidence includes: name, age, grade (single subject), telephone and gender

student = {
   'name': 'De FA Wang',
    'age': '18',
    'score': '90',
    'tel': '1335667788',
    'gender': 'male'
}
print(student)

2. 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))

  1. Count the number of failed students
  2. Print the name of the failed minor student and the corresponding score
  3. Find the average age of all boys
  4. The student's name printed at the end of the mobile phone is 8
  5. Print the highest score and the corresponding student's name
  6. Delete all students of Unknown Gender
  7. Sort the list according to the students' grades from big to small (struggle, give up if you can't)
#Count the number of failed students
count = 0
for stu in students:
    if stu['score'] < 60:
        count += 1
print(count)

# Print the name of the failed minor student and the corresponding score
for stu in students:
    if (stu['score'] < 60) and (stu['age'] < 18):
        print(stu['name'],stu['score'])

# Find the average age of all boys
count = 0
sums = 0
for stu in students:
    if stu['gender'] == 'male':
        sums += stu['age']
        count += 1
print(sums / count)

# The student's name printed at the end of the mobile phone is 8
for stu in students:
    if int(stu['tel']) % 10 == 8:
        print(stu['name'])

# Print the highest score and the corresponding student's name
max = 0
for stu in students:
    a = stu['score']
    if a > max :
        max = a
name = [stu['name'] for stu in students if stu['score']  == max]
print(max,name)

# Delete all students of Unknown Gender
for stu in students:
    if stu['gender'] == 'Unknown':
        del students[students.index(stu)]
print(students)

# Sort the list by student grade from large to small
i = 0
for x in range(len(students) - 1):
    for y in range(i + 1, len(students)):
        if students[x]['score'] < students[y]['score']:
            students[x], students[y] = students[y], students[x]
    i += 1
print(students)

3. 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': 'Classroom 12, 3rd floor, Xiaojiahe building',
    'lecturer': {
        'name': 'Yu Ting',
        'gender': 'female',
        'QQ': '726550822'
    },
    'class_teacher': {
        'name': 'Rui Yan Zhang',
        'gender': 'female',
        'QQ': '307976641'
    },
    'students': [
        {'name': 'Zhang San', 'gender': 'male', 'age': 21,  'education': 'undergraduate','QQ': '2497706075'},
        {'name': 'Li Si', 'gender': 'male', 'age': 20,  'education': 'specialty','QQ': '247435633' },
        {'name': 'WangTwo ', 'gender': 'male', 'age': 28,  'education': 'undergraduate','QQ': '467445574'}
    ]
}
  1. 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'}
]
  1. Use the list derivation to obtain the breeds of all dogs

    ['silver fox', 'fadou', 'earth dog', 'husky', 'silver fox', 'earth dog']

  2. Use list derivation to get the names of all white dogs

    ['Beibei', 'Coke']

  3. Add "male" to dogs without gender in dogs

  4. Count the number of 'silver foxes'

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'}
]

# 1. Use the list derivation to obtain the breeds of all dogs
reslut = [dog['breed'] for dog in dogs  ]
print(reslut)

# 2. Use the list derivation to obtain the names of all white dogs
reslut = [dog['name'] for dog in dogs if dog['color'] == 'white']
print(reslut)

# 3. Add "male" to dogs without gender in dogs
[dog.setdefault('gender', 'common') for dog in dogs ]
print(dogs)

# 4. Count the number of 'silver foxes'
count = 0
for dog in dogs:
    if dog['breed'] == 'Silver Fox':
        count += 1
print(count)

Keywords: Python

Added by tcl4p on Wed, 23 Feb 2022 18:16:15 +0200