Dictionaries are another variable container model that can store objects of any type.

A dictionary is also a common data structure provided by Python, which is used to hold data with mapping relationships.

Since keys in a dictionary are critical data and the program needs keys to access values, keys in a dictionary are not allowed to be repeated.

Create a dictionary

You can use {} syntax to create a dictionary

You can also use the dict() function to create dictionaries

Creating an empty dictionary

empty_dict = {}
print(empty_dict, type(empty_dict))

empty_dict_2 = dict(a)print(empty_dict_2, type(empty_dict_2))

# output
# {} <class 'dict'>
# {} <class 'dict'>
Copy the code

Create a dictionary with data

language = {
    'Chinese': 'Chinese'.'Japanese': 'Japanese'.'French': 'French'
}
print(language, type(language))

# output
# {' Chinese ':' Chinese ', 'Japanese' : 'Japanese', 'French' : 'French'} < class > 'dict'
Copy the code

In the use ofdict()When a function creates a dictionary, it can pass multiple list or tuple arguments as key-value pairs. Each list or tuple will be treated as a key-value pair, so these lists or tuples can only contain two elements.

data_1 = [('name'.O 'strange'), ('age'.18), ('address'.'chengdu')]
dict_1 = dict(data_1)

print(dict_1, type(dict_1))

# output
O # {' name ':' strange ', 'age: 18,' address ':' chengdu '} < class > 'dict'

data_2 = [['name'.O 'strange'], ['age'.18], ['address'.'chengdu']]
dict_2 = dict(data_2)

print(dict_2, type(dict_2))

# output
O # {' name ':' strange ', 'age: 18,' address ':' chengdu '} < class > 'dict'
Copy the code

It can also be passed asdict To create a dictionary by specifying a keyword argument, the key of the dictionary is not allowed to use an expression

dict_3 = dict(name=O 'strange', age=18, address='chengdu')
print(dict_3, type(dict_3))

# output
O # {' name ':' strange ', 'age: 18,' address ':' chengdu '} < class > 'dict'
Copy the code

Basic dictionary usage

The dictionary contains multiple key-value pairs, and the key is the key data of the dictionary, so the program operates on the dictionary based on the key

  • The value is accessed through the key.
  • Add a key-value pair by using a key.
  • Delete a key-value pair by key.
  • Use key to modify the key-value pair.
  • Determine whether the specified key-value pair exists based on the key.
  • Accessing a value via a key uses the same square bracket syntax as for lists and tuples, except that instead of the index in a list or tuple, you place a key in square brackets.

The value is accessed through the key

dict_4 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
print(dict_4['name'], dict_4['phone'])

# output
Blame o # 1518 * * * - * * * * - * * *
Copy the code

To add data to the bitdictionary, simply assign a value to a nonexistent key

dict_5 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
dict_5['mail'] = '2537*****.com'

print(dict_5['mail'])
print(dict_5)

# output
# 2537*****.com
O # {' name ':' strange ', 'age: 18,' address ':' chengdu ', 'phone' : '1518 * * * - * * * * - * * *' and 'mail', '2537 * * * * *. Com'}
Copy the code

If you assign a value to an existing key-value in the dictionary, the new value overrides the old value

Dict_6 = {' name ':' o blame ', 'age: 18,' address ':' chengdu ', 'phone' : '1518 * * * - * * * * - * * *'} dict_6 [' phone '] = '1999999999999999' print (dict_6 [' phone ']) print output (dict_6) # # 1999999999999999 # O {' name ':' strange ', 'age: 18,' address ':' chengdu ', 'phone', '1999999999999999'}Copy the code

To delete the key-value pair in the dictionary, usedelstatements

dict_7 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
del dict_7['phone']

print(dict_7)

# output
# {'name': 'aiguai ', 'age': 18, 'address':' aiguai '}
Copy the code

To determine whether the dictionary contains the specified key, use in or not in

dict_8 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}

# in is True if it exists; False if it does not
print('height' in dict_8)

# output False
Copy the code

Dictionary common methods

**clear()**

Clear () is used to clear all key-value pairs in the dictionary. After the clear() method is executed on a dictionary, it becomes an empty dictionary.

dict_9 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
dict_9.clear()

print(dict_9)
# output
# {}
Copy the code

get()

The get() method, which simply gets a value based on a key, is an enhanced version of the square bracket syntax that raises a KeyError when accessing a non-existent key using square bracket syntax. But if you use the get() method to access a nonexistent key, the method simply returns None without causing an error.

dict_10 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}

print(dict_10.get('name'))
print(dict_10.get('height'))

# output
O # blame
# None
Copy the code

pop()

The pop() method is used to get the value corresponding to the specified key and delete the key-value pair.

dict_11 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
dict_11.pop('age')

print(dict_11)
# output
O # {' name ':' strange ', 'address' : 'chengdu', 'phone' : '1518 * * * - * * * * - * * *'}
Copy the code

popitem()

Randomly returns and deletes the last pair of keys and values in the dictionary.

dict_12 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}

print(dict_12.popitem())
print(dict_12)

# output
# ('phone', '1518***-****-***')
# {'name': 'aiguai ', 'age': 18, 'address':' aiguai '}
Copy the code

update()

The update() method updates an existing dictionary using the key-value pairs contained in a dictionary. When the update() method is executed, if the dictionary to be updated already contains the corresponding key-value pair, then the original value will be overwritten. If the updated dictionary does not contain the corresponding key-value pair, the key-value pair is added to the dictionary.

dict_13 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
dict_13.update({'age': 999.'height': '175cm'})

print(dict_13)
# output
O # {' name ':' strange ', 'age: 999,' address ':' chengdu ', 'phone' : '1518 * * * - * * * * - * * *' and 'height' : '175 cm}
Copy the code

Dictionary traversal method

Traverse the key values

dict_14 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
for key in dict_14:
    print(key, '- >', dict_14[key])

# output
# name --> < p style = "text-align: center
# age ---> 18
# address --> Chengdu
# phone ---> 1518***-****-***
Copy the code

Through the value value

dict_15 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
for value in dict_15.values():
    print(value)

# output
O # blame
# 18
# chengdu
# 1518 * * * - * * * * - * * *
Copy the code

Iterate over dictionary keys

dict_16 = {'name': O 'strange'.'age': 18.'address': 'chengdu'.'phone': '1518 * * * - * * * * - * * *'}
for key, value in dict_16.items():
    print(key, ':', value)

# output
# name: A monster
# age : 18
# Address: Chengdu
# phone : 1518***-****-***
Copy the code