Python data structure: dictionary (dict)

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right


dictionary

The dictionary is a very important python data structure. Whether it is back-end development, crawler, data analysis, or artificial intelligence, the methods and principles of the dictionary are used.

dictionary definition

Unlike strings, lists, and tuples, a dictionary is a mutable, unordered collection of maps, containing a series of "key : value" pairs.
Dictionaries are mutable, so key-value pairs can be added, deleted, and modified.
Dictionaries are unordered collections of maps, so dictionaries cannot be indexed and sliced.

dictionary creation

Create with symbols

Use curly braces {} to create a dictionary, as an example:

>>> d1 = {
    
    'name':'lilei', 'age':20, 'grade':'three'} # 字符串作为键
>>> print(d1)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}

>>> d2 = {
    
    } # 使用{}创建空字典
>>> print(d2)
{
    
    }

>>> d3 = {
    
    (1,2,3):'a', (10001,): 1002} # 使用元组作为键
>>> print(d3)
{
    
    (1, 2, 3): 'a', (10001,): 1002}

>>> d4 = {
    
    100.1:100, 1002:200} # 使用数值型作为键,不能使用0开头的数值作为键,会报错
>>> print(d4)
{
    
    100.1:100, 1002:200}

>>> d5 = {
    
    [1,2,3]:'a', [4,5,6]:[7,8,9]} # 使用列表作为键会报错
>>> print(d5)
Traceback (most recent call last):
  File "\test.py", line 1, in <module>
    d5 = {
    
    [1,2,3]:'a', [4,5,6]:[7,8,9]}
TypeError: unhashable type: 'list'

Notice:

  • The keys of the dictionary can be immutable types such as strings, numbers, tuples, etc., and the list is a variable type and cannot be used as the keys of the dictionary;
  • The value of the dictionary can be of any type;
  • Numerical types cannot start with 0 when used as a dictionary key;
  • The keys of the dictionary cannot be repeated. If they are repeated, only the following key-value pairs are retained;
  • Dictionaries store references to objects, not the objects themselves.

Create with function

Use the dict() function to convert other types to dictionaries, examples are as follows:

>>> s1 = [('name', 'lilei'), ('age', 20), ('grade', 'three')] # 使用包含键元组和值元组的列表创建字典
>>> d1 = dict(s1)
>>> print(d1)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}

>>> d2 = dict(name='lilei', age=20, grade='three') # 使用赋值格式的键值对创建字典
>>> print(d2)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}

Get dictionary elements

A dictionary is an unordered collection of maps, and the dictionary does not have the function of indexing and slicing. The dictionary gets the corresponding value by key, the syntax is as follows:

dict[key]

The syntax of using a key to get a value in a dictionary is similar to that of a sequence index, using [].

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1['name'])
lilei
>>> print(d1['age'])
20

dictionary element added

1. Use the assignment number "=" to add key-value pairs to the dictionary

The syntax is as follows:

dict[key] = value

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> d1['sex'] = 'male' # 'sex'键不存在,为字典添加该键值对
>>> print(d1)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three', 'sex': 'male'}

When adding a key-value pair to a dictionary, the dictionary will determine whether the key exists in the dictionary. If it does not exist, add a key-value pair to the dictionary. If it exists, modify the value of the key to a new value. The reason is that the keys of the dictionary cannot be repeated. .

2. Use the update() method to add key-value pairs

The syntax is as follows:

dict.update(dict2)

parameter:

  • dict2 – The dictionary to add to the specified dictionary dict.

Return value: No return value.

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> d2 = {
    
    'math':95, 'chinese':92, 'english': 90}
>>> d1.update(d2)
>>> print(d1)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three', 'math': 95, 'chinese': 92, 'english': 90}

dictionary element deletion

1.del statement delete

Use the del statement to delete key-value pairs in the dictionary without returning a value. The syntax is as follows:

del dict[key]

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> del d1['name']
>>> print(d1)
{
    
    'age': 20, 'grade': 'three'}

2. The pop method deletes

Remove the key from the dictionary and return the mapped value, the syntax is as follows:

dict.pop(key[,default])

parameter:

  • key: the key to delete
  • default: If there is no key, return the default value, if no default is specified, an error will be reported.

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.pop('age')) # 返回'age'键对应的值
20
>>> print(d1)
{
    
    'name': 'lilei', 'grade': 'three'}

>>> print(d1.pop('class', None)) # 字典中没有'class'键,返回设置的默认是None
None

3. The popitem method deletes

The popitem() method randomly returns and removes the last key and value pair in the dictionary. If the dictionary is already empty, but this method is called, a KeyError exception is reported. The syntax is as follows:

dict.popitem()

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.popitem())
('grade', 'three')

Note: The dictionary is unordered. The keys of the dictionary in Python 3.5 and earlier versions are unordered (the order of each output is inconsistent). In versions after Python 3.5, the key-value pairs of the dictionary are output in a fixed order.

dictionary element modification

The syntax for modifying elements in a dictionary is the same as for adding elements:

dict[key] = value

When adding or modifying elements to a dictionary, the dictionary will determine whether the key exists, if it exists, modify the value of the key, and if it does not exist, add a key-value pair. The example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> d1['age'] = 21 # 'age'键存在,修改该键的值为21
>>> print(d1)
{
    
    'name': 'lilei', 'age': 21, 'grade': 'three', 'sex': 'male'}

Loop through dictionary keys

Dictionaries are iterable objects, and you can use the for loop to traverse the key-value pairs in the dictionary, but you need to use the three methods keys(), values() and items() of the dictionary, which are used to return dictionary keys A view object of value pairs. The view object supports iteration operations. Examples are as follows:

Use the keys() method to loop over the keys of a dictionary

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.keys())
dict_keys(['name', 'age', 'grade']) # 视图对象不是列表,不支持索引

# 使用for循环遍历字典的键
>>> for key in d1.keys():
... 	print(key)
name
age
grade

Use the values() method to loop over the values ​​of a dictionary

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.values())
dict_values(['lilei', 20, 'three'])

# 使用for循环遍历字典的值
>>> for value in d1.values():
... 	print(value)
lilei
20
three

Use the items() method to loop over dictionary key-value pairs

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.items())
dict_items([('name', 'lilei'), ('age', 20), ('grade', 'three')])

# 使用for循环遍历字典的键值对
>>> for item in d1.items():
... 	print(item) # item是元组
('name', 'lilei')
('age', 20)
('grade', 'three')

# 使用key, value两个变量接收items()返回值
>>> for key, value in d1.items():
... 	print(key, value) 
name lilei
age 20
grade three

dictionary function

Some methods are provided in the dictionary, and some commonly used methods are described below:

1. Empty the dictionary

The clear() method can delete all elements in the dictionary. The syntax is as follows:

dict.clear()

No parameters, no return value. An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> d1.clear() # 清空字典的所有元素
>>> print(d1) 
{
    
    }

2. Copy the dictionary

The copy() method can perform a shallow copy of the dictionary, the syntax is as follows:

dict.copy()

No arguments, returns a shallow copy of a dictionary. An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> d2 = d1.copy()
>>> print(d2)
{
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}

# 使用id()函数测试两个字典的内存地址
>>> print(id(d1))
1886511206528
>>> print(id(d2)) # 两个字典的内存地址完全不同,d2引用了新的字典对象
1886511206720

Note: Shallow copy can only copy one level, if there are multiple levels in the dictionary, other levels still refer to the same object.

3. Get the value of the specified key

The get() method can return the value of the specified key, the syntax is as follows:

dict.get(key, default=None)

parameter:

  • key – The key to look up in the dictionary.
  • default – Returns the default value if the specified key does not exist. Returns None if no default value is specified.

An example is as follows:

>>> d1 = {
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}
>>> print(d1.get('name')) 
lilei

>>> print(d1.get('class', 'nothing'))
nothing

Note: The effect of the get() method is the same as that of the dictionary getting the value dict[key] through the key, the difference is that using the get() method will not report an error if the key is not found, and using dict[key] will report an error if there is no such key in the dictionary: KeyError.

The above are the methods that the dictionary must master. It is very important to be familiar with the various methods and operations of mastering the dictionary.

Guess you like

Origin blog.csdn.net/shield911/article/details/124110525