# day8 dictionary and homework

Posted by prashanth0626 on Wed, 23 Feb 2022 15:42:34 +0100

### day8 summary

• Cognitive dictionary
• Basic operation of dictionary
• Addition, deletion and modification of dictionary
• Dictionary related operation functions and methods
• Dictionary derivation (understanding)
###### 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), and use the dictionary if the meaning of multiple data is different.

2. Cognitive Dictionary (dict)

a. 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

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

c. Requirements for elements

Keys: keys are immutable types of data (numbers, strings, Booleans, primitives, etc.) keys are unique

Value: the value is not required

```# 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}
```
###### 2, Basic operation of dictionary
1. Look up - gets 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, no error will be reported, and the default value will be returned
"""

2. ergodic

for key in Dictionary:

for key, value in dictionary items():

###### 3, Addition and deletion dictionary

```"""
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)
"""
```
2. Delete - delete key value pair (understand)

```"""
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
"""
```
###### 4, Dictionary related operation functions and methods
1. 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

2. 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
"""
```
3. correlation method

Dictionaries. clear()

Dictionaries. copy()

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 the elements are tuples consisting of each pair of keys and values

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

###### 5, Dictionary derivation
1. 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)
```

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

```stu = {'name': 'Dasima', 'age': '35', 'mark': '100 branch', 'tel': '182000000', 'sex': 'male'}
```
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))

```stu = [
{'name': 'Dasima', 'gender': 'male', 'age': 18, 'score': 100, 'tel': '1811231'},
{'name': 'Crisp', 'gender': 'female', 'age': 20, 'score': 98, 'tel': '1811232'},
{'name': 'theshy', 'gender': 'male', 'age': 32, 'score': 90, 'tel': '1811233'},
{'name': 'Yu Shuang', 'gender': 'female', 'age': 22, 'score': 70, 'tel': '1811234'},
{'name': 'Guan Zeyuan', 'gender': 'male', 'age': 28, 'score': 100, 'tel': '1811235'},
{'name': 'Lolita', 'gender': 'Unknown', 'age': 17, 'score': 99, 'tel': '1811238'},
]
```
1. Count the number of failed students

```count = 0
for x in stu:
if x['score'] < 60:
count += 1
print('Number of boys:', count)
```
2. Print the name of the failed minor student and the corresponding score

```result = 0
for x in stu:
if x['score'] < 60 and x['age'] < 18:
result = x['name']
print(result, x['score'])
```
3. Find the average age of all boys

```result = 0
count = 0
for x in stu:
if x['gender'] == 'male':
result += x['age']
count += 1
print('average age:', result / count)
```
4. The student's name printed at the end of the mobile phone is 8

```result = 0
for x in stu:
if int(x['tel']) % 10 == 8:
result = x['name']
print(result)
```
5. Print the highest score and the corresponding student's name

```max_score = max(stu1['score'] for stu1 in stu)
names = [stu1['name'] for stu1 in stu if stu1['score'] == max_score]
print(names,max_score)
```
6. Delete all students of Unknown Gender

```result=[]
for x in stu:
if x['gender'] != 'Unknown':
result.append(x)
print(result)
```
7. Sort the list according to the students' grades from big to small (struggle, give up if you can't)

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)

```class12 = {    'name': 'python2201',    'address': '12 classroom',    'lecturer': {        'name': 'Yu Ting',        'gender': 'female',        'age': 20,        'tel': '13678192302'    },    'class_teacher': {        'name': 'Rui Yan Zhang',        'gender': 'female',        'tel': '110',        'age': 20,        'QQ': '617818271'    },    'students': [        {'name': 'Dasima', 'gender': 'male', 'age': 18, 'score': 100, 'education': 'specialty', 'linkman': {'name': 'Xiao Wu', 'tel': '110'}},        {'name': 'Crisp', 'gender': 'female', 'age': 20, 'score': 98, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Zhang', 'tel': '120'}},        {'name': 'Broiler', 'gender': 'male', 'age': 30, 'score': 90, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Zhao', 'tel': '119'}},        {'name': 'Shy man', 'gender': 'male', 'age': 22, 'score': 70, 'education': 'specialty', 'linkman': {'name': 'Xiao Liu', 'tel': '134'}},        {'name': 'Xiao Ming', 'gender': 'male', 'age': 28, 'score': 100, 'education': 'undergraduate', 'linkman': {'name': 'Xiao Xu', 'tel': '2383'}},        {'name': 'Yu Shuang', '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'}}    ]}
```
4. 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']

```result = [x['breed'] for x in dogs]result = {x: x for x in range(10) if x % 3}print(result)
```
2. Use list derivation to get the names of all white dogs

['Beibei', 'Coke']

```result = [x['name'] for x in dogs if x['color'] == 'white']print(result)
```
3. Add "male" to dogs without gender in dogs

```for x in dogs:    x.setdefault('gender', 'common')print(dogs)
```
4. Count the number of 'silver foxes'

```count = 0for x in dogs:    if x['breed'] == 'Silver Fox':        count += 1print(count)
```

Topics: Python