Python3 Dictionary

A dictionary is another kind of mutable container model that can store objects of any type.

Each key-value pair of a dictionarykey=>valuepair is separated by a colon:separated, and each pair is separated by a comma (,) separated, the entire dictionary is enclosed in curly braces{}, the format is as follows:

d = {key1 : value1, key2 : value2, key3 : value3 }

Note:dictAs Python keywords and built-in functions, variable names are not recommended to be nameddict。

Keys must be unique, but values need not be.

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

A simple dictionary example:

tinydict = {'name': 'example', 'likes': 123, 'url': 'www.example.com'}

You can also create a dictionary like this:

tinydict1 = { 'abc': 456 }
tinydict2 = { 'abc': 123, 98.6: 37 }

Create an empty dictionary

Use curly braces{ }to create an empty dictionary:

Example

# Use curly braces {} to create an empty dictionary
emptyDict = {}
 
# Print the dictionary
print(emptyDict)
 
# Check the number of dictionary items
print("Length:", len(emptyDict))
 
# Check the type
print(type(emptyDict))

The above example outputs:

{}
Length: 0
<class 'dict'>

Use the built-in functiondict()to create a dictionary:

Example

emptyDict = dict()
 
# Print the dictionary
print(emptyDict)
 
# Check the number of dictionary items
print("Length:",len(emptyDict))
 
# Check the type
print(type(emptyDict))

The above example outputs:

{}
Length: 0
<class 'dict'>

Access values in a dictionary

Put the corresponding key inside square brackets, as in the example below:

Example

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

The above example outputs:

tinydict['Name']:  Example
tinydict['Age']:  7

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

Example

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

The above example outputs:

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


Modify dictionary

The way to add new content to a dictionary is to add new key/value pairs, or modify or delete existing key/value pairs, as in the following example:

Example

#!/usr/bin/python3 tinydict = {'Name': 'Example', 'Age': 7, 'Class': 'First'} tinydict['Age'] = 8 # Update Age tinydict['School'] = "Example Tutorial" # Add information print ("tinydict['Age']: ", tinydict['Age']) print ("tinydict['School']: ", tinydict['School'])
The above example outputs:
tinydict['Age']:  8
tinydict['School']:  Example


Delete dictionary elements

You can delete a single element or clear the dictionary; clearing only requires one operation.

Explicitly delete a dictionary using the del command, as in the following example:

Example

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

But this will raise an exception, because the dictionary no longer exists after the del operation:

Traceback (most recent call last):
  File "/example-test/test.py", line 9, in <module>
    print ("tinydict['Age']: ", tinydict['Age'])
NameError: name 'tinydict' is not defined

Note:The del() method will also be discussed later.


Characteristics of dictionary keys

Dictionary values can be any Python object, either standard objects or user-defined objects, but keys cannot.

Two important points need to be remembered:

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

Example

#!/usr/bin/python3 tinydict = {'Name': 'Example', 'Age': 7, 'Name': 'Little Rookie'} print ("tinydict['Name']: ", tinydict['Name'])

The above example outputs:

tinydict['Name']:  小Example

2) Keys must be immutable, so numbers, strings, or tuples can be used, but lists cannot, as in the following example:

Example

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

The above example outputs:

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


Dictionary built-in functions & methods

Python dictionaries contain the following built-in functions:

No.Function and descriptionExample
1len(dict)
Count the number of dictionary elements, i.e., the total number of keys.
>>> tinydict = {'Name': 'Example', 'Age': 7, 'Class': 'First'}
>>> len(tinydict)
3
2str(dict)
Output the dictionary, a printable string representation.
>>> tinydict = {'Name': 'Example', 'Age': 7, 'Class': 'First'}
>>> str(tinydict)
"{'Name': 'Example', 'Class': 'First', 'Age': 7}"
3type(variable)
Return the type of the input variable. If the variable is a dictionary, return the dictionary type.
>>> tinydict = {'Name': 'Example', 'Age': 7, 'Class': 'First'}
>>> type(tinydict)
<class 'dict'>

Python dictionaries contain the following built-in methods:

No.Function and description
1dict.clear()
Delete all elements in the dictionary
2dict.copy()
Return a shallow copy of a dictionary
3dict.fromkeys()
Create a new dictionary, using elements in the sequence seq as the keys of the dictionary, and val as the initial value corresponding to all keys of the dictionary
4dict.get(key, default=None)
Return the value of the specified key. If the key is not in the dictionary, return the default value set by default.
5key in dict
Return true if the key is in the dictionary dict, otherwise return false.
6dict.items()
Return a view object as a list
7dict.keys()
Return a view object
8dict.setdefault(key, default=None)
Similar to get(), but if the key does not exist in the dictionary, the key will be added and its value set to default.
9dict.update(dict2)
Update the key/value pairs of dictionary dict2 into dict.
10dict.values()
Return a view object
11dict.pop(key[,default])
Delete the value corresponding to the key in the dictionary and return the deleted value.
12 dict.popitem()
Return and delete the last key-value pair in the dictionary.
Other extensions