[Python] This article takes you to learn dictionaries and collections in data structures

 

Author's homepage: boy who loves to laugh. Blog_CSDN blog - deep learning, activities, python field blogger loves to laugh boy. A boy who is good at deep learning, activities, python, etc., and loves to laugh. Focus on algorithms, python, computer vision, image processing, deep learning, pytorch, neural network, opencv fields. https://blog.csdn.net/Code_and516?type=blog Personal profile: Dagong.

Continue to share: machine learning, deep learning, python-related content, daily BUG solutions, and Windows&Linux practical tips.

If you find an error in the article, please point it out, and I will correct it in time. If you have other needs, you can private message me or send me an email: [email protected] 

Dictionaries and sets in Python are two important data structures that are often used in practical programming. 

This article will explain in detail the dictionaries and collections in the Python data structure


Table of contents

1. Dictionary

1.1 Introduction to the dictionary

1.2 History of dictionary development

1.3 Application scenarios of dictionaries

1.4 How to use the dictionary

1.4.1 Create a dictionary

(1) Use curly braces to create an empty dictionary

(2) Create a dictionary using key-value pairs

(3) Use the dict() function to create a dictionary

1.4.2 Accessing dictionary elements

1.4.3 Modify dictionary elements

1.4.4 Adding dictionary elements

1.4.5 Delete dictionary elements 

1.4.6 Traversing the dictionary

(1) Traverse keys

(2) traverse the value

(3) Traversing key-value pairs

1.4.7 Dictionary methods

(1) keys(): returns all the keys in the dictionary

(2) values(): returns all the values ​​in the dictionary

(3) items(): returns all key-value pairs in the dictionary

(4) pop(key): Delete the key-value pair of the specified key in the dictionary and return the deleted value

(5) clear(): Delete all key-value pairs in the dictionary

(6) copy(): copy dictionary

1.5 Summary of dictionaries

Two, collection

2.1 Introduction to collections

2.2 History of collection development

2.3 Application Scenarios of Collections

2.4 How to use collections

2.4.1 Create collection

(1) Use curly braces to create an empty collection

(2) Use the set() function to create a collection

2.4.2 Basic operations on collections

(1) Add elements

(2) Delete elements

(3) Determine whether the element exists

2.4.3 Set operations

(1) Intersection

(2) Union

(3) difference set

(4) Symmetric difference set

2.4.4 Traversing collections

2.4.5 Collection methods

(1) add(element): add elements to the collection

(2) remove(element): remove elements from the collection

(3) pop(): Randomly delete and return an element in the collection

(4) clear(): Clear all elements in the collection

(5) copy(): copy collection

2.5 Summary of collections

3. Summary


1. Dictionary

1.1 Introduction to the dictionary

        A dictionary is a mutable, unordered, key-value pair data structure in Python. It is composed of a series of keys and corresponding values. Keys are unique and values ​​can be repeated. There is no clear order between the key-value pairs in the dictionary, and the corresponding value is accessed through the key. Dictionaries are represented by curly braces {}, colons: are used to separate keys and values, and commas are used to separate key-value pairs. For example:

student = {"name": "Tom", "age": 18, "gender": "male"}

1.2 History of dictionary development

        Dictionaries in Python were first designed and implemented by Dutch computer scientist Guido van Rossum in the mid-1980s. In earlier versions, the implementation of the dictionary used the data structure of the hash table (Hash Table), which is a data structure that supports fast insertion, deletion, and lookup. Early Python dictionary implementations were inspired by dictionaries in other programming languages ​​such as Perl, with some optimizations. Due to the characteristics of the hash table, Python's dictionary has good performance and has become one of the core data structures in the Python language.

        As Python has evolved, dictionaries have undergone further improvements in syntax and performance. Here are some milestones in the history of Python dictionaries.

  1. Python 2.0 In version 2.0 of Python, some significant improvements were made to the internal implementation of dictionaries. A new hashing algorithm and a solution to hash collisions are introduced. These improvements improve the performance and stability of the dictionary, making the dictionary better able to handle large-scale data collection operations.

  2. Python 3.6 In Python 3.6, the syntax of dictionaries has been improved a bit. A new literal syntax has been added. Simplified expressions can be used when creating dictionaries, which improves the readability and simplicity of the code. For example, curly braces {} can be used to create an empty dictionary, and a colon : can be used to specify key-value pairs.

  3. Python 3.7 In Python 3.7, key-value pairs in dictionaries are kept in insertion order. This means that the elements in the dictionary will be traversed in the order they were inserted, not out of order. This improvement provides better predictability and reliability, making dictionaries more useful in certain application scenarios.

        Currently, dictionaries in Python are very mature and stable. In the version iterations of Python, dictionaries have always been an object of focus and improvement to meet various application needs.

1.3 Application scenarios of dictionaries

        Dictionaries have a wide range of uses, and common application scenarios include:

  1. Data storage: Dictionaries can be used to store data that needs to be accessed through key-value pairs, such as storing student grades, employee salaries, etc.
  2. Data processing: Dictionaries can be used to group, classify, and summarize data, and the corresponding values ​​can be quickly looked up and accessed through the characteristics of keys.
  3. Data transfer: Dictionaries can be used as parameters and return values ​​of functions to transfer and return multiple related values.

1.4 How to use the dictionary

1.4.1 Create a dictionary

        We can create dictionaries in several ways:

(1) Use curly braces to create an empty dictionary

my_dict = {}
print(my_dict)  # 输出:{}

(2) Create a dictionary using key-value pairs

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(my_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}

(3) Use the dict() function to create a dictionary

my_dict = dict(name='Tom', age=20, gender='male')
print(my_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}

1.4.2 Accessing dictionary elements

        We can access the values ​​in the dictionary by key:

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(my_dict['name'])  # 输出:Tom
print(my_dict['age'])  # 输出:20

        Note: If the accessed key does not exist in the dictionary, a KeyError exception will be thrown. You can use get()methods to avoid exceptions: 

print(my_dict.get('name'))  # 输出:Tom
print(my_dict.get('height'))  # 输出:None

1.4.3 Modify dictionary elements

        The elements in the dictionary are mutable, and we can modify the value directly through the key:

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
my_dict['age'] = 22
print(my_dict)  # 输出:{'name': 'Tom', 'age': 22, 'gender': 'male'}

1.4.4 Adding dictionary elements

        We can add dictionary elements by setting a new key-value pair:

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
my_dict['height'] = 180
print(my_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male', 'height': 180}

1.4.5 Delete dictionary elements 

        We can use delthe statement to remove elements from a dictionary: 

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
del my_dict['age']
print(my_dict)  # 输出:{'name': 'Tom', 'gender': 'male'}

1.4.6 Traversing the dictionary

        We can foriterate over the keys or values ​​of a dictionary using a loop:

(1) Traverse keys

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
for key in my_dict.keys():
    print(key)
# 输出:
# name
# age
# gender

(2) traverse the value

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
for value in my_dict.values():
    print(value)
# 输出:
# Tom
# 20
# male

(3) Traversing key-value pairs

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
for key, value in my_dict.items():
    print(key, value)
# 输出:
# name Tom
# age 20
# gender male

1.4.7 Dictionary methods

        Dictionaries provide a series of commonly used methods, the following are some commonly used dictionary methods:

(1) keys(): Return all the keys in the dictionary

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(my_dict.keys())  # 输出:dict_keys(['name', 'age', 'gender'])

(2) values(): Return all the values ​​in the dictionary

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(my_dict.values())  # 输出:dict_values(['Tom', 20, 'male'])

(3) items(): Return all key-value pairs in the dictionary

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(my_dict.items())  # 输出:dict_items([('name', 'Tom'), ('age', 20), ('gender', 'male')])

(4)pop(key): Delete the key-value pair of the specified key in the dictionary and return the deleted value

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
value = my_dict.pop('age')
print(my_dict)  # 输出:{'name': 'Tom', 'gender': 'male'}
print(value)  # 输出:20

(5)clear(): delete all key-value pairs in the dictionary

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
my_dict.clear()
print(my_dict)  # 输出:{}

(6)copy(): copy dictionary

my_dict = {'name': 'Tom', 'age': 20, 'gender': 'male'}
new_dict = my_dict.copy()
print(new_dict)  # 输出:{'name': 'Tom', 'age': 20, 'gender': 'male'}

1.5 Summary of dictionaries

        As a core data structure, a dictionary has the following characteristics and advantages:

  1. Flexibility: Dictionaries can store any type of data, can be nested and combined, and are applicable to various complex data scenarios.
  2. Fast lookup: The dictionary stores and accesses data in the form of key-value pairs, which can still provide fast access speed when the amount of data is large.
  3. Mutability: The keys and values ​​in the dictionary can be modified, added or deleted at any time, making the dictionary more dynamic.
  4. Insertion order preservation: Since Python 3.7, elements in dictionaries are traversed in the order they were inserted, providing better predictability and reliability.

        In short, dictionaries are very important and practical data structures in the Python language, with a wide range of application scenarios. It has undergone many improvements and optimizations in the history of Python development, continuously improving performance and stability. In actual programming, proficient use of dictionaries can improve the efficiency and maintainability of programs.

Two, collection

2.1 Introduction to collections

        A set is a data structure in Python used to store unique elements. It can store any type of data, but each element can only appear once in the collection. A set is an unordered set of distinct elements. In Python, collections are represented by curly braces {}, and elements are separated by commas. For example:

fruits = {"apple", "orange", "banana"}

2.2 History of collection development

        Sets, as an important data structure, have been continuously improved and optimized during the development of Python. Here are some milestones in the history of Python collections.

  1. Python 2.3 In the Python 2.3 version, collections (set) were first introduced into Python as a basic data type. The introduction of collections enables Python to have richer data structures and operations, providing more options for program development.

  2. Python 2.6 In Python 2.6, collections introduce new operators and methods that enhance the functionality and flexibility of collections. Added set-related operators, such as union operator |, intersection operator &, difference operator -, etc., to facilitate comparison and operation between sets.

  3. Python 3.0 In Python 3.0, the internal implementation of collections has been improved and optimized. A more efficient hash table implementation is used, improving the performance and stability of collections. At the same time, the collection supports more operations and methods, making the usage of the collection more flexible and convenient.

2.3 Application Scenarios of Collections

        The uses of collections mainly include:

  1. Data deduplication: The uniqueness of elements in the collection ensures that there is no duplicate data, which can be used for deduplication operations.
  2. Data association: Sets can be used to compare, calculate, and process associations between data, such as intersecting sets, union sets, and difference sets.
  3. Data filtering: the collection can filter data according to certain conditions, and extract elements that meet the conditions.

2.4 How to use collections

2.4.1 Create collection

        We can create collections in several ways:

(1) Use curly braces to create an empty collection

my_set = set()
print(my_set)  # 输出:set()

(2) Use set()functions to create collections

my_set = set([1, 2, 3, 3, 4])
print(my_set)  # 输出:{1, 2, 3, 4}

2.4.2 Basic operations on collections

        Collections provide a series of common operations, such as adding elements, deleting elements, determining whether an element exists, and so on.

(1) Add elements

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 输出:{1, 2, 3, 4}

(2) Delete elements

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # 输出:{1, 3}

(3) Determine whether the element exists

my_set = {1, 2, 3}
print(2 in my_set)  # 输出:True

2.4.3 Set operations

        Sets can perform operations such as intersection, union, and difference.

(1) Intersection

python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1.intersection(set2)
print(intersection)  # 输出:{2, 3}

(2) Union

set1 = {1, 2, 3}
set2 = {2, 3, 4}
union = set1.union(set2)
print(union)  # 输出:{1, 2, 3, 4}

(3) difference set

set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference = set1.difference(set2)
print(difference)  # 输出:{1}

(4) Symmetric difference set

set1 = {1, 2, 3}
set2 = {2, 3, 4}
symmetric_difference = set1.symmetric_difference(set2)
print(symmetric_difference)  # 输出:{1, 4}

2.4.4 Traversing collections

        We can use fora loop to iterate over the collection:

my_set = {1, 2, 3}
for item in my_set:
    print(item)
# 输出:
# 1
# 2
# 3

2.4.5 Collection methods

        Collection provides a series of commonly used methods, the following are some commonly used collection methods:

(1) add(element): Add elements to the collection

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 输出:{1, 2, 3, 4}

(2) remove(element): Remove elements from the collection

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)  # 输出:{1, 3}

(3) pop(): Randomly delete and return an element in the collection

my_set = {1, 2, 3}
item = my_set.pop()
print(my_set)  # 输出:{2, 3}
print(item)  # 输出:1

(4) clear(): Clear all elements in the collection

my_set = {1, 2, 3}
my_set.clear()
print(my_set)  # 输出:set()

(5) copy(): copy collection

my_set = {1, 2, 3}
new_set = my_set.copy()
print(new_set)  # 输出:{1, 2, 3}

2.5 Summary of collections

        Collection is a commonly used data structure in Python, which has the following characteristics and advantages:

  1. Uniqueness: The elements in the collection are unique and can be used for deduplication operations to improve the quality and accuracy of data.
  2. Unorderedness: The elements in the collection have no clear order, and can be quickly searched and manipulated in scenes that do not care about the order.
  3. Mutability: elements in the collection can be added or deleted at any time, suitable for dynamic data processing and association operations.
  4. Efficiency: The uniqueness of the elements in the collection and the implementation of the hash table ensure the high efficiency and good performance of the collection.

        All in all, set is one of the very useful data structures in Python for storing unique elements and performing data manipulation. With the development of Python, collections have been continuously improved and optimized in syntax and performance to adapt to different application scenarios. Proficient use of collections can improve the efficiency of the program and the readability of the code.

3. Summary

        Dictionaries and sets are commonly used data structures in Python. The dictionary is used to store key-value pairs, the corresponding value can be accessed through the key, and supports adding, deleting and updating elements. Sets are used to store a set of unordered and unique elements, and support operations such as addition, deletion, intersection, and union. In actual programming, continuous familiarity and flexible use of dictionaries and collections can improve the efficiency and readability of code.

 

Guess you like

Origin blog.csdn.net/Code_and516/article/details/131471910