Consolidate the foundation of Python (4)

Consolidate the Python foundation

Four, dictionary

In the "Introduction to Python" course, we learned the four major data structures of Python: lists, tuples, dictionaries and sets. Among them, the dictionary is probably the most difficult to understand and not very good at using data structure.

In today's course, we will consolidate our knowledge of dictionaries and expand our application skills.

(1) Basic concepts

Actually, the main reason that the dictionary is not easy to understand is that its structure is a little more complicated. Everyone likes simple things and doesn't bother much.

But sometimes things that are a little bit more complicated can be even more effortless. What do you say?

Let's put it this way, many students who are not familiar with computer hardware are speechless when faced with a piece of computer accessories that have been taken apart, that is, a pile of garbage. However, in the eyes of the little brother in the computer city, it is completely different. In a few minutes, it can be assembled into a complete computer. Do you still understand this matter? It’s not because of how powerful the computer brother is, but the principle of each chip or integrated circuit of these accessories is actually at a loss. However, when they are integrated together, they become a component, and the little brother only needs to know which one. The thing is the motherboard, that piece is the memory, that piece is the hard disk, etc., he can easily assemble it into a computer. So, what's great is the person who integrates chips and circuits into one component, and it is he/they who made it easier to assemble computers.

Going back to our data structure, why does the type of dictionary, which are slightly more complicated than lists, tuples and sets, have its advantages? For example, everyone has a height. If a certain data collection project just needs such a bunch of data, a lot of people, hundreds, thousands, or tens of thousands, if there is a list on hand, let everyone group them in order. Measure the height, and then record the ID and height data of each person. If we save the ID in a list, and then save the height in a list, obviously, the amount of data in the two lists is the same. There is also a one-to-one correspondence. However, if only one data in a certain list is moved, will the data be completely messed up?

So, a good solution is to record the ID and height data in pairs. In this way, although a single data record is a bit more complicated, it can be used when one is obtained, and each data is complete and effective. Because, we made it the simplest "integration", it is no longer an isolated data, but an effective data unit. This is like a computer component, it becomes usable, and we don't need to mind why they are together? Is it the right combination? Because that's the right thing for those who collect and record the data. The data structure that they built to record ID and height in pairs is a dictionary!

In fact, in real life, almost everything is related, and connected data is meaningful. Therefore, a large number of data we face exist in this way.

Learning to use a dictionary will make you even more powerful when dealing with data!

1、 Definition dictionary

For example, in the above case, if there is a group of collected objects with IDs: 1001, 1002, 1003, 1004, 1005, their height measurements are: 172, 169, 180, 178, and 183 (meters).

Then, we can use a dictionary to express as:

{1001:172, 1002:169, 1003:180, 1004:178, 1005:183}

A dictionary is a data structure that records information with a mapping relationship. The so-called mapping relationship is a word that is frequently used in the software field. In real life, we often call it "one-to-one correspondence". The title is not important. The important thing is to understand its connotation. There is always a "one-to-one correspondence" state in any mapping relationship. In Python, it is called a "key-value" relationship (Key-Value) because it Each set of data is a "key-value pair". For example, the above ID is unique, it represents different measurement objects (people), it is the key (Key), and the height is the value (Value) corresponding to the ID (Key).

2、 Features of the dictionary

Obviously, in this kind of dictionary data mapping relationship, the key is unique. Think about it, if it is not unique, what will happen? For example, once the ID above is duplicated, then the height data corresponding to it cannot know whose height it belongs to? Right? !

This is why we did not use names to create the keys of the dictionary.

3、 Common operations of the dictionary

(1) Create a dictionary

dict1 = {1001:172, 1002:169, 1003:180, 1004:178, 1005:183}

(2) Read dictionary data

dict1[1001]# Get the corresponding value by key

172

(3) Add dictionary data

dict1[1006:176]

dict1

{1001:172, 1002:169, 1003:180, 1004:178, 1005:183, 1006:176}

(4) Modify dictionary data

dict1[(1002:168)]

dict1

{1001:172, 1002:168, 1003:180, 1004:178, 1005:183, 1006:176}

(5) Convert other data types to dictionaries

list1 = [('Chinese',83),('Mathematics',98),('English',90)]

dict2 = dict(list1)

dict2

{ 'Language': 83,'Mathematics': 98,'English': 90}

(6) get() method: read Value according to Key

print(dict1.get(1003))

180

**Please note that ** does it get the same result as dict1[1003]? That's right! However, the value of the get() method is that if a key does not exist, such as dict1[1007], Python will report an error, but dict1.get(1007) will not report an error, and it will return you a value of none.

(7) update() method: append the data of one dictionary to another dictionary

dict3 = dict1.update(dict2)

dict3

{1001:172, 1002:168, 1003:180, 1004:178, 1005:183, 1006:176, 'Language': 83,'Mathematics': 98,'English': 90}

**It should be noted that: **When the update() method is executed, if the updated dictionary contains the corresponding key-value pair, the original value will be overwritten; if the updated dictionary does not contain the corresponding key-value Yes, the key-value pair is added.

(8) pop(key) method: delete the key-value pair of the specified key, and return the value of the specified key

dict1.pop(1006)

176

dict1

{1001:172, 1002:169, 1003:180, 1004:178, 1005:183}

(9) clear() method: used to clear all key-value pairs of the dictionary

dict2.clear()

dict2

{}

(10) In key: Determine whether a key-value pair exists? Return True / False

1007 in dict1

False

(11) Dictionary loop (note the difference between the two)

info = {

' stu_1001':"Lan Wu",

' stu_1002':"Long Lou la",

' stu_1003':"Xiao Ze",

}

Basic cycle, high efficiency

for i in info:

print(i,info[i])

This loop is a bit more complicated, but the result is easy to read

for k,v in info.items():
print(k,v)

**Due to space limitations, there are some other commonly used methods in the dictionary. It is recommended to visit the Gaodu website. There are a large number of Python courses and micro-class materials for learning, reading and querying. **

(2) Multi-level nesting of dictionaries

Python's data structure can be nested in multiple levels. Of course, dictionaries are also possible. Therefore, a dictionary object can carry a large number of and complex data information. Below, let's enjoy it:

Information of some provinces and municipalities

province_city_area_dict = {

"Hubei":{

"Wuhan City": ['Jiang'an District','Jianghan District','Qiaokou District','Hanyang District','Wuchang District','Qingshan District','Hongshan District','Dongxihu District','Hannan District','Caidian District','Jiangxia District','Huangpi District','Xinzhou District'],

"Huangshi City": ['Huangshi Port District','Xisai Mountain Area','Xialu District','Tieshan District','Yangxin County','Daye City'],

"Yichang City": ['Xiling District','Wujiagang District','Dian Military District','Xiaoting District','Yiling District','Yuan'an County','Xingshan County','Zigui County','Changyang Tujia Autonomous County','Wufeng Tujia Autonomous County','Yidu City','Dangyang City','Zhijiang City']

},

"Hunan":{

"Changsha City": ['Furong District','Tianxin District','Yuelu District','Kaifu District','Yuhua District','Changsha County','Wangcheng County','Ningxiang County',' Liuyang City'],

"Zhuzhou City": ['Lotus Pond District','Lusong District','Shifeng District','Tianyuan District','Zhuzhou County','You County','Chaling County','Yanling County',' Liling City'],

"Xiangtan City":['Yuhu District','Yuetang District','Xiangtan County','Xiangxiang City','Shaoshan City']

},

"Guangdong":{

"Guangzhou City": ['Dongshan District','Liwan District','Yuexiu District','Haizhu District','Tianhe District','Fangcun District','Baiyun District','Huangpu District','Panyu District' ,'Huadu District','Zengcheng','Conghua City'],

"Shenzhen City": ['Luohu District','Futian District','Nanshan District','Baoan District','Longgang District','Yantian District'],

"Zhuhai City":['Xiangzhou District','Doumen District','Jinwan District']

}

}

**Code analysis: **

We see that the information of some provinces and municipalities is created in a two-level nested dictionary.

The first level: The key is the province, and the value is a dictionary corresponding to the information of some cities and districts in the province.

The second level: the key is the name of the city, and the value is a list of district names contained in the city.

In fact, you can imagine that the information of all provinces, cities, regions (counties) in the country can be stored in such a two-level nested dictionary to store all data information.

OK, if there is such a function in the program:

def my_function(a):

Function code block (omitted)

We need to pass this data object to a function to participate in the processing of other more data, then we only need to do it like this:

my_function(province_city_area_dict)

**Is it super simple? **

This is what we just said at the beginning, sometimes something a little bit more complicated can be more effortless. Proficiency in the use of dictionaries can minimize the complexity of our code writing.

(3) Case: A three-level linkage menu

In the following case, you can use the above dictionary data to easily create a three-level linkage menu. Everyone, it is best to manually type the following code into your computer, open Python Sell and run the code to immediately experience a three-level linkage menu effect on provinces, cities, and regions.

def city_menu(data):

for i in data:

print(i)

choie1 = input("The province you want to choose is:")

if choie1 in data:

for j in data[choie1]:

print(j)

choie2 = input("The city you want to choose is:")

if choie2 in data[choie1]:

for k in data[choie1][choie2]:

print(k)

choie3 = input("The region/county you want to select is:")

if choie3 in data[choie1][choie2]:

print("The area you selected is: "+choie1+"province"+choie2+choie3+"!")

else:

print("Your input is wrong!")

else:

print("Your input is wrong!")

else:

print("Your input is wrong!")

# Call functions

city_menu‍(province_city_area_dict)

Of course, the above code is only used to demonstrate how to use dictionary data. As a menu program for commercial development, it is generally not written in this way, and the function will be more in line with the habits of use.

Interested students can modify the above code and write a three-level linkage menu that truly belongs to them.

I believe you can do it! Come on! ! !

Recommended Posts

Consolidate the foundation of Python (4)
Consolidate the foundation of Python(7)
Consolidate the foundation of Python(6)
Consolidate the foundation of Python(5)
Consolidate the foundation of Python (3)
Consolidate the Python foundation (2)
"Consolidating the Foundation of Python" (1)
The usage of wheel in python
Python handles the 4 wheels of Chinese
Python simulation of the landlord deal
What is the use of Python
The premise of Python string pooling
Secrets of the new features of Python 3.8
The father of Python joins Microsoft
The operation of python access hdfs
The usage of tuples in python
End the method of running python
Understanding the meaning of rb in python
Can Python implement the structure of the stack?
Learn the basics of python interactive mode
What are the required parameters of python
Logistic regression at the bottom of python
The usage of Ajax in Python3 crawler
Python solves the Tower of Hanoi game
Solve the conflict of multiple versions of python
7 features of Python3.9
What is the scope of python variables
Python implements the sum of fractional sequences
Two days of learning the basics of Python
What is the id function of python
Where is the pip path of python3
The essence of Python language: Itertools library
2.3 Python language foundation
What are the advantages of python language
The specific method of python instantiation object
2.1 The Python Interpreter (python interpreter)
python3 realizes the function of mask drawing
What is the prospect of python development
What is the function body of python
The specific method of python import library
Solve the conflict of multiple versions of python
What is the function of adb in python
Detailed explanation of the principle of Python super() method
The difference between the syntax of java and python
Python realizes the development of student management system
Python implements the shuffling of the cards in Doudizhu
The meaning and usage of lists in python
Solve the problem of python running startup error
Can the value of the python dictionary be modified?
Python implements the source code of the snake game
Detailed explanation of the usage of Python decimal module
How about learning python at the age of 27?
The consequences of uninstalling python in ubuntu, very
Python writes the game implementation of fishing master
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
09. Common modules of Python3
[898] python get the intersection of two lists | union | difference
Detailed explanation of the principle of Python function parameter classification