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:

d = {key1 : value1, key2 : value2 }

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 = {'a': 1, 'b': 2, 'b': '3'}
>>> 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:

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

You can also create a dictionary like this:

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

Accessing Values in a Dictionary

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

Example

#!/usr/bin/python tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "tinydict['Name']: ", tinydict['Name'] print "tinydict['Age']: ", tinydict['Age']

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

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

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

#!/usr/bin/python # -*- coding: UTF-8 -*- tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} tinydict['Age'] = 8 # Update tinydict['School'] = "EXAMPLE" # Add print "tinydict['Age']: ", tinydict['Age'] print "tinydict['School']: ", tinydict['School']
The output of the above example is:
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

#!/usr/bin/python # -*- coding: UTF-8 -*- tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del tinydict['Name'] # Delete entry with key 'Name' tinydict.clear() # Clear all entries in the dictionary del tinydict # Delete dictionary print "tinydict['Age']: ", tinydict['Age'] print "tinydict['School']: ", tinydict['School']

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

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

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

#!/usr/bin/python tinydict = {['Name']: 'Zara', 'Age': 7} print "tinydict['Name']: ", tinydict['Name']

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 numberFunction and description
1cmp(dict1, dict2)
Compares elements of two dictionaries.
2len(dict)
Counts the number of dictionary elements, i.e., the total number of keys.
3str(dict)
Outputs a printable string representation of the dictionary.
4type(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 numberFunction and description
1dict.clear()
Deletes all elements in the dictionary.
2dict.copy()
Returns a shallow copy of a dictionary.
3dict.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.
4dict.get(key, default=None)
Returns the value of the specified key. If the key is not in the dictionary, returns the default value.
5dict.has_key(key)
Returns true if the key is in the dictionary dict, otherwise returns false.Not supported in Python3.
6dict.items()
Returns a traversable array of (key, value) tuples as a list.
7dict.keys()
Returns a list of all keys in a dictionary.
8dict.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.
9dict.update(dict2)
Updates the key/value pairs of dictionary dict2 into dict.
10dict.values()
Returns a list of all values in a dictionary.
11pop(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.
Other extensions