Python Dictionary
A dictionary is another mutable container model that can store objects of any type.
Each key-value pair of the dictionarykey:valueis separated by a colon:and each key-value pair is separated by a comma,and the entire dictionary is enclosed in curly braces{}as shown in the following format:
Note:dictAs Python keywords and built-in functions, it is not recommended to name variablesdict。
Keys are generally unique. If a duplicate key appears, the last key-value pair will replace the previous one. Values do not need to be unique.
>>> tinydict['b']
'3'
>>> tinydict
{'a': 1, 'b': '3'}
Values can be of any data type, but keys must be immutable, such as strings, numbers, or tuples.
A simple dictionary example:
You can also create a dictionary like this:
Accessing Values in a Dictionary
Put the corresponding key inside the familiar square brackets, as in the following example:
Example
The output of the above example is:
tinydict['Name']: Zara tinydict['Age']: 7
If you use a key that does not exist in the dictionary to access data, an error will be output as follows:
Example
The output of the above example is:
tinydict['Alice']:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print "tinydict['Alice']: ", tinydict['Alice']
KeyError: 'Alice'
Modifying a Dictionary
The way to add new content to a dictionary is to add new key/value pairs, modify or delete existing key/value pairs as shown in the following example:
Example
tinydict['Age']: 8 tinydict['School']: EXAMPLE
Deleting Dictionary Elements
You can delete a single element or clear the entire dictionary. Clearing requires only one operation.
To explicitly delete a dictionary, use the del command, as in the following example:
Example
But this will raise an exception, because after using del, the dictionary no longer exists:
tinydict['Age']:
Traceback (most recent call last):
File "test.py", line 10, 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 without limitation, either standard objects or user-defined ones, but keys cannot.
Two important points to remember:
1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:
Example
The output of the above example is:
tinydict['Name']: Manni
2) Keys must be immutable, so numbers, strings, or tuples can be used, but lists cannot, as in the following example:
Example
The output of the above example is:
Traceback (most recent call last):
File "test.py", line 3, in <module>
tinydict = {['Name']: 'Zara', 'Age': 7}
TypeError: unhashable type: 'list'
Dictionary Built-in Functions & Methods
The Python dictionary includes the following built-in functions:
| Serial number | Function and description |
|---|---|
| 1 | cmp(dict1, dict2) Compares elements of two dictionaries. |
| 2 | len(dict) Counts the number of dictionary elements, i.e., the total number of keys. |
| 3 | str(dict) Outputs a printable string representation of the dictionary. |
| 4 | type(variable) Returns the input variable type. If the variable is a dictionary, it returns the dictionary type. |
The Python dictionary includes the following built-in methods:
| Serial number | Function and description |
|---|---|
| 1 | dict.clear() Deletes all elements in the dictionary. |
| 2 | dict.copy() Returns a shallow copy of a dictionary. |
| 3 | dict.fromkeys(seq[, val]) Creates a new dictionary, using elements from sequence seq as keys of the dictionary, and val as the initial value corresponding to all keys. |
| 4 | dict.get(key, default=None) Returns the value of the specified key. If the key is not in the dictionary, returns the default value. |
| 5 | dict.has_key(key) Returns true if the key is in the dictionary dict, otherwise returns false.Not supported in Python3. |
| 6 | dict.items() Returns a traversable array of (key, value) tuples as a list. |
| 7 | dict.keys() Returns a list of all keys in a dictionary. |
| 8 | dict.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. |
| 9 | dict.update(dict2) Updates the key/value pairs of dictionary dict2 into dict. |
| 10 | dict.values() Returns a list of all values in a dictionary. |
| 11 | pop(key[,default]) Deletes the value corresponding to the given key in the dictionary, and returns the deleted value. The key value must be given. Otherwise, returns the default value. |
| 12 | popitem() Returns and deletes the last key-value pair in the dictionary. |