Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the common data structure of Python

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the common data structure of Python". In the daily operation, I believe that many people have doubts about what the common data structure of Python is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "what is the common data structure of Python?" Next, please follow the editor to study!

For example, if we want to save a person's information, including name, age, weight, unit address, home address, personal mobile phone number, emergency contact mobile number, etc., you will find that the lists, tuples and collections we have learned before are not the best choices.

Person1 = ['Wang Da Hammer', 55, 60,'62 Kehua North Road','8 Zhong Tongren Road', '13122334455,' 13800998877']

Person2 = ('Wang Da Hammer', 55, 60,'62 Kehua North Road','8 Zhong Tongren Road', '13122334455,' 13800998877')

Person3 = {'Wang Da Hammer', 55, 60,'62 Kehua North Road','8 Zhong Tongren Road', '13122334455qu,' 13800998877'}

The set must be the most inappropriate, because the set has the feature of deduplication, and if a person has the same age and weight, there will be one less item of information in the set; similarly, if the person's home address and unit address are the same, then there will be one less item of information in the collection. On the other hand, although lists and tuples can save all a person's information, when you want to get that person's mobile phone number, you need to know whether his mobile phone number is the sixth or seventh element in the list or tuple; when you want to get a person's home address, you also need to know which item in the list or tuple. In short, lists, tuples, and dictionaries are not the most appropriate choices in the above scenarios, and we also need the dictionary type, which is the best data type for assembling related information together and can help us solve the problem of modeling real things in the program.

When it comes to the word dictionary, we must be no stranger. When we were in primary school, everyone basically had a "Xinhua Dictionary", as shown in the following picture.

The dictionary in the Python program is very similar to the dictionary in real life. It organizes the data in the way of key-value pairs (the combination of keys and values), and we can find the corresponding values through keys and operate them. Just like in Xinhua Dictionary, each word (key) has its corresponding interpretation (value), each word and its interpretation together is an entry in the dictionary, and the dictionary usually contains many such entries.

Create and use dictionaries

To create a dictionary in Python, you can use the {} literal syntax, which is the same as the collection in the previous lesson. But the elements in the dictionary {} exist in the form of key-value pairs, each consisting of two values separated by:: preceded by a key, followed by a value, and the code is shown below.

Xinhua = {

'Foothills': 'foot of the mountain', 'road': 'road, place of passage; area: southern goods, foreign goods; species: they are one person'

Xishui, the name of the water, that is, the Zhuozhang River in present-day Shanxi Province, and the name of Lu River, the name of the Nujiang River in Yunnan Province.

}

Print (xinhua)

Person = {

'name': 'Wang sledgehammer,' age': 55, 'weight': 60,' office':'62 Kehua North Road

8 Tongren Road, 'home':', 'tel':' 13122334455, 'econtact':' 13800998877'

}

Print (person)

From the above code, I believe you can see that using a dictionary to save a person's information is far better than using lists or tuples, because we can use: the previous key to express the meaning of the entry, and: behind is the corresponding value of this entry.

Of course, if you prefer, we can also use the built-in function dict or the dictionary's generative syntax to create the dictionary, as shown below.

Each set of parameters in the # dict function (constructor) is a set of key-value pairs in the dictionary

Person = dict (name=' King sledgehammer', age=55, weight=60, 8 'Tongren Road, home=')

Print (person) # {'name':' Wang sledgehammer', 'age': 55,' weight': 60, No. 8 Tongren Road, 'home':'

# you can compress two sequences and create a dictionary through the Python built-in function zip

Items1 = dict (zip ('ABCDE',' 12345'))

Print (items1) # {'Aids:' 1miles, 'bands:' 2bands, 'codes:' 3bands, 'codes:' 4bands, 'eats:' 5'}

Items2 = dict (zip ('ABCDE', range (1,10)

Print (items2) # {'Agar: 1,' Barrier: 2, 'Che: 3,' Dust: 4, 'Egg: 5}

# create dictionaries with dictionary generative syntax

Items3 = {x: X * * 3 for x in range (1,6)}

Print (items3) # {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

If you want to know how many key-value pairs there are in the dictionary, you can still use the len function; if you want to traverse the dictionary, you can use the for loop, but you should note that the for loop only traverses the keys in the dictionary, but it doesn't matter, after talking about the dictionary operation, we can get the corresponding value through the keys in the dictionary.

Person = {'name':' Wang sledgehammer', 'age': 55,' weight': 60, 'office':' 62 Kehua North Road'}

Print (len (person)) # 4

For key in person:

Operation of print (key) dictionary

For dictionary types, member operation and index operation are certainly the most important. The former can determine whether the specified key is in the dictionary, while the latter can obtain the corresponding value through the key or add a new key-value pair to the dictionary. It is worth noting that the index of the dictionary is different from the index of the list, because the elements in the list have their own sequence numbers, so the index of the list is an integer; because what is saved in the dictionary is the key of the key-value pair, so the index of the dictionary is the key in the key-value pair, and the index operation can modify the original value or store a new key-value pair in the dictionary. Need to remind you that the keys in the dictionary must be immutable types, such as integer (int), floating point (float), string (str), tuple (tuple) and other types of values; obviously, lists (list) and sets (set) can not be used as keys in the dictionary, of course, dictionary types themselves can no longer be used as keys in dictionaries, because dictionaries are also mutable types, but dictionaries can be used as values in dictionaries. The reasons why mutable types cannot be used as keys in dictionaries will be explained in detail later in the course. Here, let's take a look at the following code to understand the dictionary membership operation and index operation.

Person = {'name':' Wang sledgehammer', 'age': 55,' weight': 60, 'office':' 62 Kehua North Road'}

# check whether the name and tel keys are in the person dictionary

Print ('name' in person,' tel' in person) # True False

# change the corresponding value in the person dictionary to 25 through age revision

If 'age' in person:

Person ['age'] = 25

# storing new key-value pairs in the person dictionary through index operation

Person ['tel'] =' 13122334455'

Person ['signature'] =' your boyfriend is a piece of junk, he will step on colorful auspicious clouds to win your best friend'

Print ('name' in person,' tel' in person) # True True

# check the number of key-value pairs in the person dictionary

Print (len (person)) # 6

# Loop the key of the dictionary and get the corresponding value of the key through indexing operation

For key in person:

Print (f'{key}: {person [key]}')

It should be noted that when getting the value in the dictionary through the index operation, if the specified key is not in the dictionary, a KeyError exception will be thrown.

The method of dictionary

Dictionary type methods are basically related to dictionary key-value pair operations, and you can use the following examples to understand the use of these methods. For example, we want to use a dictionary to store students' information, we can use the student's student number as the key in the dictionary, and we can get the corresponding student by indexing the student's student number; we can also make a dictionary with the corresponding values of the keys in the dictionary, so that we can use multiple groups of key-value pairs to store students' name, gender, age, place of origin and other information, as shown below.

# the value in the dictionary is another dictionary (nested dictionary)

Students = {

1001: {'name':' Di Renjie', 'sex': True,' age': 22, 'place':' Shanxi Datong'}

1002: {'name':' Bai Yuanfang', 'sex': True,' age': 23, 'place':' Hebei Baoding'}

1003: {'name':' Wu Zetian, 'sex': False,' age': 20, 'place':' Sichuan Guangyuan'}

}

# use the get method to get the corresponding value through the key. If you can't get it, it will not throw a KeyError exception but return None or the default value set.

Print (students.get (1002)) # {'name':' Bai Yuanfang', 'sex': True,' age': 23, 'place':' Hebei Baoding'}

Print (students.get (1005)) # None

Print (students.get (1005, {'name':' John Doe'})) # {'name':' anonymous'}

# get all the keys in the dictionary

Print (students.keys ()) # dict_keys ([1001, 1002, 1003])

# get all the values in the dictionary

Print (students.values ()) # dict_values ([{...}, {...}, {...}])

# get all the key-value pairs in the dictionary

Print (students.items ()) # dict_items ([(1001, {...}), (1002, {....}), (1003, {...})]))

# iterate through all the key-value pairs in the dictionary

For key, value in students.items ():

Print (key,'-->', value)

# use the pop method to delete the corresponding key-value pair through the key and return the value

Stu1 = students.pop (1002)

Print (stu1) # {'name':' Bai Yuanfang', 'sex': True,' age': 23, 'place':' Hebei Baoding'}

Print (len (students)) # 2

# stu2 = students.pop (1005) # KeyError: 1005

Stu2 = students.pop (1005, {})

Print (stu2) # {}

# use the popitem method to delete the last set of key-value pairs in the dictionary and return the corresponding tuple

# if there are no elements in the dictionary, calling this method will throw a KeyError exception

Key, value = students.popitem ()

Print (key, value) # 1003 {'name':' Wu Zetian', 'sex': False,' age': 20, 'place':' Sichuan Guangyuan'}

# setdefault can update the value of the key in the dictionary or deposit a new key-value pair in the dictionary

The first parameter of the # setdefault method is the key, and the second parameter is the value corresponding to the key

# if the key exists in the dictionary, updating the key will return the original value corresponding to the key

# if this key does not exist in the dictionary, the method returns the value of the second parameter, which defaults to None

Result = students.setdefault (1005, {'name':' Fang Qihe', 'sex': True})

Print (result) # {'name':' Fang Qihe', 'sex': True}

Print (students) # {1001: {...}, 1005: {...}}

# use update to update dictionary elements, the same key will overwrite the old value with the new value, and different keys will be added to the dictionary

Others = {

1005: {'name':' Qiao Feng', 'sex': True,' age': 32, 'place':' Beijing Daxing'}

1010: {'name':' Wang Yuyan, 'sex': False,' age': 19}

1008: {'name':' Zhong Ling, 'sex': False}

}

Students.update (others)

Print (students) # {1001: {...}, 1005: {...}, 1010: {...}, 1008: {...}}

Like the list, you can use the del keyword to delete an element from the dictionary. If the specified key index does not reach the corresponding value, it will also throw a KeyError exception, as shown below.

Person = {'name':' King sledgehammer', 'age': 25,' sex': True}

Del person ['age']

Application of print (person) # {'name':' Wang Da Hammer', 'sex': True} Dictionary

We use a few simple examples to explain the application of dictionaries.

Example 1: enter a paragraph to count the number of times each English letter appears.

Sentence = input ('Please enter a paragraph:')

Counter = {}

For ch in sentence:

If'A'

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report