[Deep Learning] Python and NumPy Series Tutorials (6): Python Container: 4. Detailed explanation of Dictionary (initialization, accessing elements, common operations, common functions, traversal, parsing)

Table of contents

I. Introduction

2. Experimental environment

3. Python Containers (Containers)

0. Introduction to containers

4. Dictionary

0. Basic concepts

1. Initialization

a. Use {} to create a dictionary

b. Create a dictionary using the dict() function

2. Access dictionary elements

a. Use square brackets []

b. Use the get() method

3. Common operations on dictionary

a. Add or modify elements

b. Delete elements

c. Determine whether the key exists

d. Dictionary length

4. Common functions of dictionaries

keys(): returns all keys in the dictionary

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

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

copy(): copy dictionary

clear(): clears all elements in the dictionary

5. Traverse

a. Traverse keys (Keys)

b. Traverse values ​​(Values)

c. Traversing key-value pairs (Items)

6. Dictionary analysis


I. Introduction

        Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.

        Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:

  • Python: basic data types, containers (lists, tuples, sets, dictionaries), functions, classes
  • Numpy: arrays, array indexing, data types, array math, broadcasting
  • Matplotlib: plots, subplots, images
  • IPython: Creating notebooks, typical workflow

2. Experimental environment

        Python 3.7

        Run the following command to check the Python version

 python --version 

3. Python Containers (Containers)

0. Introduction to containers

        Containers in Python are objects used to store and organize data. Common containers include List, Tuple, Set and Dictionary.

  • Lists are ordered mutable containers that can contain elements of different types and are created using square brackets ([]).
my_list = [1, 2, 3, 'a', 'b', 'c']
  • Tuples are ordered immutable containers that can also contain elements of different types and are created using parentheses (()).
my_tuple = (1, 2, 3, 'a', 'b', 'c')
  • A set is an unordered and non-duplicate container used to store unique elements. It is created using curly brackets ({}) or the set() function.
my_set = {1, 2, 3, 'a', 'b', 'c'}
  •  A dictionary is an unordered container of key-value pairs used to store values ​​with unique keys. It is created using curly braces ({}) or the dict() function.
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

        These containers provide different methods and operations for storing, accessing and processing data. The appropriate container type can be selected based on specific needs.

1. List

[Deep Learning] Python and NumPy Series Tutorials (3): Python Container: 1. Detailed explanation of List (initialization, indexing, slicing, updating, deletion, common functions, unpacking, traversal)_QomolangmaH's blog-CSDN blog https: icon-default.png?t=N7T8// blog.csdn.net/m0_63834988/article/details/132768246?spm=1001.2014.3001.5501

2. Tuple

[Deep Learning] Python and NumPy Series Tutorials (4): Python Container: 2. Detailed explanation of tuples (initialization, indexing and slicing, tuple characteristics, common operations, unpacking, traversal)_QomolangmaH's blog-CSDN blog https: icon-default.png?t=N7T8/ /blog.csdn.net/m0_63834988/article/details/132777307?spm=1001.2014.3001.5501

3. Set

[Deep Learning] Python and NumPy Series Tutorials (V): Python Container: 3. Detailed explanation of Set (initialization, access elements, common operations, common functions)_QomolangmaH's blog-CSDN blog icon-default.png?t=N7T8https://blog.csdn.net/m0_63834988 /article/details/132779181?spm=1001.2014.3001.5502

4. Dictionary

0. Basic concepts

        A dictionary is a mutable, unordered collection of key-value pairs. The elements in the dictionary are composed of keys and corresponding values. Each key and value are separated by a colon (:). The entire key-value pair is separated by a comma (,), and the entire dictionary is included. in curly braces ({}).

  • Key-value pair (key, value): The key is an extension of the data index.
    • Key: immutable data type
      • Numbers (integers/floating point numbers), strings, tuples, etc.
    • Value: any data type
  • Basic pattern: {<key1>:<value1>, <key2>:<value2>, … , <keyn>:<valuen>}

1. Initialization

a. {}Create a dictionary using

        Use curly braces ({}) to create an empty dictionary, or initialize a non-empty dictionary with key-value pairs.

# 创建一个空字典
empty_dict = {}

# 创建一个非空字典
student = {"name": "John", "age": 20, "grade": "A"}

b. Using dict()a function to create a dictionary

  dict()Functions that create dictionaries by passing key-value pairs or iterable objects such as tuples or lists.

  • Pass parameters
student = dict(name="John", age=20, grade="A")
  • through iterable objects
student_info = [("name", "John"), ("age", 20), ("grade", "A")]
student = dict(student_info)

2. Access dictionary elements

a. Use square brackets []

        The values ​​in the dictionary can be accessed by keys.

student = {"name": "John", "age": 20, "grade": "A"}

print(student["name"])
print(student["age"])

The output is:

John
20

b.  get() How to use

        get() Methods can accept a key as a parameter and return the corresponding value. get() The method returns  if the key does not exist in the dictionary, Noneor a default value can be provided as the  get() second argument to the method to return if the key does not exist.

student = {"name": "John", "age": 20, "grade": "A"}

print(student.get("name"))
print(student.get("address", "N/A"))

The output is:

John
N/A

3. Common operations on dictionary

a. Add or modify elements

        Use assignment statements to add or modify elements in the dictionary.

student = {"name": "John", "age": 20, "grade": "A"}

student["age"] = 21  # 修改年龄
student["address"] = "123 Main St"  # 添加地址

print(student)

The output is:

{'name': 'John', 'age': 21, 'grade': 'A', 'address': '123 Main St'}

b. Delete elements

        Use delstatements or pop()methods to delete elements from a dictionary.

student = {"name": "John", "age": 20, "grade": "A"}

del student["age"]  # 删除年龄
student.pop("grade")  # 删除成绩

print(student)

The output is:

{'name': 'John'}

c. Determine whether the key exists

        Use inkeywords to determine whether a specified key exists in the dictionary.

student = {"name": "John", "age": 20}

print("name" in student)  # True
print("grade" in student)  # False

The output is:

True
False

d. Dictionary length

student = {"name": "John", "age": 20, "grade": "A"}
length = len(student)
print(length)  # 输出:3

        In the above example, we use len()a function to get studentthe length of the dictionary and then print the result. The result is 3, which means there are 3 key-value pairs in the dictionary.

4. Common functions of dictionaries

keys(): Returns all keys in the dictionary

values(): Returns all values ​​in the dictionary

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

copy(): Copy dictionary

clear(): Clear all elements in the dictionary

student = {"name": "John", "age": 20, "grade": "A"}

print(student.keys())
print(student.values())
print(student.items())

student_copy = student.copy()
student.clear()

print(student_copy)
print(student)

The output is:

dict_keys(['name', 'age', 'grade'])
dict_values(['John', 20, 'A'])
dict_items([('name', 'John'), ('age', 20), ('grade', 'A')])
{'name': 'John', 'age': 20, 'grade': 'A'}
{}

5. Traverse

a. Traverse keys (Keys)

        You can use keys()the method to get all the keys in the dictionary and traverse them. Examples are as follows:

student = {"name": "John", "age": 20, "grade": "A"}

for key in student.keys():
    print(key)

The output is:

name
age
grade

b. Traverse values ​​(Values)

        You can use values()the method to get all the values ​​in the dictionary and traverse them. Examples are as follows:

student = {"name": "John", "age": 20, "grade": "A"}

for value in student.values():
    print(value)

The output is:

John
20
A

c. Traversing key-value pairs (Items)

        You can use items()the method to get all the key-value pairs in the dictionary and traverse them. Examples are as follows:

student = {"name": "John", "age": 20, "grade": "A"}

for key, value in student.items():
    print(key, value)

The output is:

name John
age 20
grade A

6. Dictionary analysis

        Combine the for loop and the code that creates the new element into one line so that it automatically appends the new element.

original_dict = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}

new_dict = {key: value for key, value in original_dict.items() if value % 2 == 0}

print(new_dict)

Output:

{'b': 2, 'd': 4}

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/132780196