Detailed explanation of Python basic types and application scenarios (5)--dictionary

background

For many Python beginners, it is very difficult to understand the structure and function of each of our data.

Therefore, it is very necessary to understand the structure, expression, usage and application of each basic type in our program. This article strives to explain the relevant information of the basic type dictionary through simple and clear language

introduce

A Dictionary is an unordered data structure used to store a collection of key-value pairs. Each key (key) is unique, and the corresponding value (value) can be repeated. Dictionaries are characterized by using keys to access values, rather than using indexes. You can think of a dictionary as a phone book, where each person's name corresponds to a phone number, the name is the key, and the phone number is the value. In python, we usually use the English of the list dictto represent the dictionary

The representation of the dictionary

The expression form of a dictionary is a pair of key-value pairs enclosed by curly braces ({}), each key-value pair is separated by a colon, and each key-value pair is separated by a comma. The keys of a dictionary must be immutable types, such as strings, numbers, tuples, etc., while the values ​​can be of any type, such as strings, numbers, lists, tuples, or even another dictionary. As shown in the code below:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}

In this dictionary, 'apple', 'banana', and 'orange' are the keys, and 2, 3, and 4 are the corresponding values. The values ​​in the dictionary can be accessed in the following ways:

print(my_dict['apple'])  # 输出2

The values ​​in the dictionary can be modified or new key-value pairs can be added in the following ways:

my_dict['pear'] = 5  # 添加一个新的键值对
my_dict['banana'] = 6  # 修改键为'banana'的值为6

A key-value pair in a dictionary can be deleted using:

del my_dict['orange']  # 删除键为'orange'的键值对

The role of the dictionary

  1. Storing key-value pairs: A dictionary can store any number of key-value pairs, which can be different types of data, such as strings, numbers, lists, tuples, or even another dictionary. This makes dictionaries a very convenient way to store and organize data.

  2. Fast access: Unlike lists or tuples, the elements in a dictionary are unordered, but the corresponding value (value) can be quickly accessed through the key (key). This makes dictionaries a very fast and efficient data structure for applications that require fast lookup and access to data.

  3. Applicable to various application scenarios: Dictionaries are widely used in various application scenarios. For example, dictionaries can be used to store configuration files, record user information, store data, and more.

  4. Supports dynamic modification: Dictionaries are mutable, which means that key-value pairs can be added, removed, and modified dynamically. This makes the dictionary a very flexible data structure, which can dynamically change the content of the dictionary at runtime to meet the needs of various application scenarios.

Access dictionary values

To access the content in the dictionary, you can use the key (key) of the dictionary to obtain the corresponding value (value). There are two commonly used methods:

Use square brackets ([]) to get the value :
You can get the corresponding value by specifying the key in the square brackets. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
print(my_dict['apple'])  # 输出2

Get the corresponding value 2 by specifying the key 'apple'.

If an attempt is made to access a key that does not exist, a KeyError exception will be raised. For example:

print(my_dict['pear'])  # 抛出KeyError异常

Use the get() method to get the value:
You can use the get() method to get the corresponding value. If the specified key does not exist, return None or the specified default value. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
print(my_dict.get('apple'))  # 输出2
print(my_dict.get('pear'))  # 输出None
print(my_dict.get('pear', 0))  # 输出0

Use the get() method to specify the key to get the corresponding value. If the specified key does not exist, None will be returned; the second parameter can be passed in the get() method to specify the default value. Here, the default value is 0.

In short, to access the contents of the dictionary, you can use the keys of the dictionary to obtain the corresponding values, which can be achieved by using square brackets ([]) or the get() method.

use

Add an element to the dictionary

direct assignment

New key-value pairs can be added to the dictionary by direct assignment. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
my_dict['pear'] = 5
print(my_dict)

Add a new key-value pair by directly assigning a value to the key 'pear' of the dictionary, and the output is:

{
    
    'apple': 2, 'banana': 3, 'orange': 4, 'pear': 5}

Use the update() method

You can add new key-value pairs to a dictionary using the update() method, which accepts a dictionary as an argument and merges it into the original dictionary. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
new_dict = {
    
    'pear': 5, 'kiwi': 6}
my_dict.update(new_dict)
print(my_dict)

Merge the new dictionary new_dict into the original dictionary my_dict through the update() method, and the output result is:

{
    
    'apple': 2, 'banana': 3, 'orange': 4, 'pear': 5, 'kiwi': 6}

remove value from dictionary

use the del keyword

Use the del keyword to delete key-value pairs in a dictionary:

del my_dict[key]

Among them, my_dict is the dictionary of key-value pairs to be deleted, and key is the key to be deleted. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
del my_dict['banana']
print(my_dict)

Use the del keyword to delete the key 'banana' and its corresponding value in the dictionary, and the output is:

{
    
    'apple': 2, 'orange': 4}

Use the pop() method

Use the pop() method to delete key-value pairs in the dictionary, the syntax is:

my_dict.pop(key[, default])

where my_dict is the dictionary of key-value pairs to delete, key is the key to delete, default is an optional default value, and returns the default value if the key does not exist. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
my_dict.pop('banana')
print(my_dict)

Use the pop() method to delete the key 'banana' and its corresponding value in the dictionary, and the output is:

{
    
    'apple': 2, 'orange': 4}

Use the popitem() method

Use the popitem() method to randomly delete a key-value pair in the dictionary, the syntax is:

my_dict.popitem()

where my_dict is the dictionary of key-value pairs to delete. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
my_dict.popitem()
print(my_dict)

Use the popitem() method to randomly delete a key-value pair in the dictionary, and the output is:

{
    
    'apple': 2, 'banana': 3}

dictionary comprehension

Similar to list comprehension, dictionary comprehension is also supported in Python, which can quickly create dictionaries. For example:

my_dict = {
    
    i: i * i for i in range(1, 6)}
print(my_dict)

In this example, we use a dictionary comprehension to create a dictionary with keys 1 to 5 and values ​​corresponding to the square, and the output is:

{
    
    1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Get all the keys of the dictionary

keys() method
Use the keys() method to get all the keys in the dictionary and return a view object containing all the keys, which can be converted to a list using the list() method. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
keys = my_dict.keys()
print(keys)
print(list(keys))

In the above example, we use the keys() method to get all the keys in the dictionary my_dict, and the output is:

dict_keys(['apple', 'banana', 'orange'])
['apple', 'banana', 'orange']

Get all values ​​of the dictionary

values() method
Use the values() method to get all the values ​​in the dictionary, return a view object containing all the values, and use the list() method to convert it into a list. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
values = my_dict.values()
print(values)
print(list(values))

In the above example, use the values() method to get all the values ​​in the dictionary my_dict, and the output is:

dict_values([2, 3, 4])
[2, 3, 4]

Get all key-value pairs of the dictionary

items() method
Use the items() method to get all the key-value pairs in the dictionary, and return a view object containing all key-value pairs, which can be converted into a list using the list() method. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
items = my_dict.items()
print(items)
print(list(items))

Use the items() method to get all key-value pairs in the dictionary my_dict, and the output is:

dict_items([('apple', 2), ('banana', 3), ('orange', 4)])
[('apple', 2), ('banana', 3), ('orange', 4)]

empty dictionary

clear() method
You can use the clear() method to clear all key-value pairs in the dictionary and return an empty dictionary. For example:

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
my_dict.clear()
print(my_dict)

In this example, use the clear() method to clear all key-value pairs in the dictionary my_dict, and the output is:

{
    
    }

deep copy vs shallow copy

Dictionaries, like lists, also have the problem of deep copy and shallow copy.
Shallow copy
When using the shallow copy method copy() of a dictionary, a new dictionary object is actually created, but the elements in the dictionary are still the same as those in the original dictionary. quote. That is, the new dictionary and the original dictionary share element objects.

For example:

my_dict = {
    
    'a': [1, 2, 3], 'b': [4, 5, 6]}
new_dict = my_dict.copy()
my_dict['a'][0] = 100
print(my_dict)   # {'a': [100, 2, 3], 'b': [4, 5, 6]}
print(new_dict)  # {'a': [100, 2, 3], 'b': [4, 5, 6]}

In this example, a dictionary my_dict containing two key-value pairs is first created, and then a new dictionary new_dict is created using the copy() method. Then change the first value in the first element in my_dict to 100, and find that the first element in new_dict has also changed accordingly. This is because the elements in new_dict refer to the same objects as the elements in my_dict.

Deep copy
Deep copy will recursively copy all the elements in the dictionary to create a brand new dictionary object. You can use the deepcopy() method in the copy module to make a deep copy.

For example:

my_dict = {
    
    'a': [1, 2, 3], 'b': [4, 5, 6]}
new_dict = copy.deepcopy(my_dict)
my_dict['a'][0] = 100
print(my_dict)   # {'a': [100, 2, 3], 'b': [4, 5, 6]}
print(new_dict)  # {'a': [1, 2, 3], 'b': [4, 5, 6]}

In this example, a new dictionary object new_dict is created using the deepcopy() method in the copy module, and the elements in my_dict are copied. Then change the first value in the first element in my_dict to 100, and find that the first element in new_dict has not changed, because the elements in new_dict are brand new objects.

Guess you like

Origin blog.csdn.net/a914541185/article/details/129695503
Recommended