Python3 dictionary

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

Each key value of the dictionary (key=>value) is split with a colon (:), separated by a comma (, ). The entire dictionary is enclosed in curly braces ({}) in the following format:

d = {key1 : value1, key2 : Value2 }

key must be unique, but the value is not necessary.


value can take any data type, but the keys must be immutable, such as strings, numbers, or tuples.

A simple dictionary example:

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

You can likewise make a dictionary like this:

dict1 = { 'abc': 456 }; 

dict2 = { 'abc': 123, 98.6: 37 };

Access the incentive in the dictionary

Put the relating key in square sections, as in the accompanying example:


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

The output of the above example:

dict['Name' ]: Welookups
Dict['Age']: 7

If you access the data with a key that is not in the dictionary, the error will be output as follows:


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

The output of the above example:

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

dict['Age'] = 8; # Update Age dict['School'] = "Web tutorial" # add information print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])
The above example output:
dict['Age']: 8
dict['School']: Web tutorial

Delete dictionary elements

The ability to delete a single element can also clear the dictionary, emptying only one operation.

Show delete a dictionary with the del command, as in the following example:


#!/usr/bin/python3 dict = {'Name': 'Welookups', 'Age': 7, 'Class': 'First'} del dict['Name'] # Delete key 'Name' dict.clear() # Clear dictionary del dict # Delete dictionary print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])

This will raise an exception because the dictionary no longer exists after performing 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:del() The method will also be discussed later.。

Characteristics of dictionary keys

The dictionary value can be any python object, either a standard object or a user-defined one, but not a key.

Two important points to remember:

1) The same key is not allowed to appear twice. If the same key is assigned twice when creating, the latter value will be remembered, as in the following example:


#!/usr/bin/python3 dict = {'Name': 'Welookups', 'Age': 7, 'Name': 'Little Web'} print ("dict['Name']: ", dict['Name'])

The output of the above example:

dict['Name' ]: small Web

2) The key must be immutable, so it can be played with numbers, strings or tuples, but not with the list, as in the following example:


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

The output of the above example:

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

Dictionary built-in function & method

The Python dictionary contains the following built-in functions:

>>> dict = {'Name': 'Welookups', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>
serial numberfunction and descriptioninstance
Calculate the number of dictionary elements, which is the total number of keys。
>>> dict = {'Name': 'Welookups', 'Age': 7, 'Class': 'First'}
>>> len(dict)
Output dictionary, represented by a printable string。
>>> dict = {'Name': 'Welookups', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'Welookups', 'Class': 'First', 'Age': 7}"
Returns the input variable type, if the variable is a dictionary, returns the dictionary type。

The Python dictionary contains the following built-in methods:

serial numberfunction and description
Delete all elements in the dictionary
Return a shallow copy of a dictionary
Create a new dictionary to sequence seq The middle element is the key of the dictionary, and val is the initial value corresponding to all the keys of the dictionary
4radiansdict.get(key, default=None)
Return the specified key Value, if the value is not in the dictionary, return the default value
5key in dict
If the key returns true in the dictionary dict, otherwise Return false
Return traversable (key) in list , value) tuple array
Returns an iterator that can use list () to convert to a list
8radiansdict.setdefault(key, default=None)
Similar to get(), but if the key does not exist in the dictionary, it will add the key and set the value to default
Put the key/value of the dictionary dict2 Update to dict
Returns an iterator that can use list () to convert to a list
Delete dictionary given keys The value corresponding to key, the return value is the deleted value. The key value must be given. Otherwise, return the default value.
12 popitem()
Randomly returns and deletes a pair of keys in the dictionary And value (generally delete the last pair).

welookups is optimized for learning.© welookups 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.