A dictionary is another variable container model and can store any type of object.

Each key value of the dictionary is split with a colon ( : ) , : pair is split with a , ( , {}) , and the entire dictionary is included in the parentheses , in the following format:

d = {key1 : value1, key2 : value2 }

The key must be unique, but the value does not have to be.

Values can take any data type, but keys must be immeascondable, such as strings, numbers, or yuans.

A simple dictionary example:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can also create a dictionary like this:

dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }

Access the values in the dictionary

Put the appropriate keys into familiar square brackets, as follows:

#!/usr/bin/python3

dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}

print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

The above example output results:

dict['Name']:  W3CSchool
dict['Age']:  7

If you access data with keys that are not in the dictionary, the output error is as follows:

#!/usr/bin/python3
 
dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}
 
print ("dict['Alice']: ", dict['Alice'])

The above example output results:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'

Modify the dictionary

The way to add new content to the dictionary is to add a new key/value pair and modify or delete an existing key/value pair as follows:

#!/usr/bin/python3

dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8;               # 更新 Age
dict['School'] = "W3Cschool教程"  # 添加信息


print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
The above example output results:
dict['Age']:  8
dict['School']:  W3Cschool教程

Delete the dictionary element

Can delete a single element can also empty the dictionary, emptying only one operation.

The display removes a dictionary with the del command, as follows:

#!/usr/bin/python3

dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}

del dict['Name'] # 删除键 'Name'
dict.clear()     # 删除字典
del dict         # 删除字典

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

However, this throws an exception because the dictionary no longer exists after the del operation:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable

Note: The del() method is also discussed later.


The characteristics of the dictionary key

Dictionary values can take any Python object without restriction, neither a standard object nor a user-defined object, but the key does not.

There are two important points to keep in mind:

1) The same key is not allowed to appear twice. If the same key is assigned twice when it is created, the last value is remembered, as in the following example:

#!/usr/bin/python3

dict = {'Name': 'W3CSchool', 'Age': 7, 'Name': '小菜鸟'}

print ("dict['Name']: ", dict['Name'])

The above example output results:

dict['Name']:  小菜鸟

2) The key must be imm changeable, so you can use numbers, strings, or metagroups, but not with lists, as in the following example:

#!/usr/bin/python3

dict = {['Name']: 'W3CSchool', 'Age': 7}

print ("dict['Name']: ", dict['Name'])

The above example output results:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'W3CSchool', 'Age': 7}
TypeError: unhashable type: 'list'

Dictionary built-in functions and methods

The Python dictionary contains the following built-in functions:

Serial number Functions and descriptions Instance
1 len(dict)
Calculates the number of dictionary elements, which is the total number of keys.
>>> dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
2 str(dict)
The output dictionary is represented by a printable string.
>>> dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'W3CSchool', 'Class': 'First', 'Age': 7}"
3 type(variable)
Returns the type of variable entered, and returns the dictionary type if the variable is a dictionary.
>>> dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>

The Python dictionary contains the following built-in methods:

Serial number Functions and descriptions
1 radiansdict.clear()
Delete all elements in the dictionary
2 radiansdict.copy()
Returns a shallow copy of a dictionary
3 radiansdict.fromkeys()
Create a new dictionary with the elements in the sequence seq as the keys to the dictionary, and val is the initial value for all keys in the dictionary
4 radiansdict.get(key, default=None)
Returns the value of the specified key, if the value does not return the default value in the dictionary
5 key in dict
If the key returns true in the dictionary diction, otherwise it returns false
6 radiansdict.items()
Returns an array of traversable (key, value) yuans in a list
7 radiansdict.keys()
Returns all the keys of a dictionary in a list
8 radiansdict.setdefault(key, default=None)
Similar to get(), if the key does not exist in the dictionary, the key is added and the value is set to default
9 radiansdict.update(dict2)
Update the key/value pair of the dictionary dipt2 to the diction
10 radiansdict.values()
Returns all values in the dictionary in a list