Python Dictionary
Dictionary is another mutable container model and can store any type of object.
Each key-value (key=>value) pair in the dictionary is separated by a colon (:), and each pair is separated by a comma (,) , the entire dictionary is included in curly brackets ({}), the format is as follows:
Keys must be unique, but values do not.
The value can be of any data type, but the key must be immutable, such as string, number or tuple.
A simple dictionary example:
You can also create a dictionary like this:
dict2 = { 'abc': 123, 98.6: 37 };
Access the value in the dictionary
Put the corresponding key in the familiar square brackets, as in the following example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
Output result of the above example:
dict['Age']: 7
If you access data using keys that are not in the dictionary, the following error will be output:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
The above example output result:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Modify Dictionary
The way to add new content to the dictionary is to add new key/value pairs, modify or delete existing key/value pairs as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
dict['School']: DPS School
Delete dictionary elements
Can delete a single element or clear the dictionary , clearing only requires one operation.
To display and delete a dictionary, use the del command, as shown in the following example:
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # The delete key is' Name' entries
dict.clear(); # Clear all entries in the dictionary
del dict am ;
print "dict['School']: ", dict['School'];
print "dict[' Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Characteristics of dictionary keys
Dictionary values can take any python object without restrictions, either standard objects or user-defined, 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:
!/usr/bin/python
print "dict['Name']: ", dict[' Name'];
Output result of the above example:
2) The key must be immutable, so it can use numbers, strings or elements Group acts as a group, so using a list will not work. The following example:
dict = {['Name']: 'Zara', 'Age ': 7};
print "dict['Name']: ", dict['Name'];
Output result of the above example:
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7} ;
TypeError: list objects are unhashable
Dictionary built-in functions & methods
The Python dictionary contains the following built-in functions:
Serial number | Function and description |
---|---|
1 | cmp(dict1, dict2) Compare two Dictionary element. |
2 | len(dict) Calculate the number of dictionary elements, that is, the total number of keys. |
3 | str(dict) Output the printable string representation of the dictionary. |
4 | type(variable) 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 number | Function and description |
---|---|
1 | radiansdict.clear() Delete all elements in the dictionary |
2 | radiansdict .copy() Returns a shallow copy of the dictionary |
3 | radiansdict.fromkeys() Creates a new dictionary to sequence the elements in seq Be the key of the dictionary, val is the initial value corresponding to all keys in the dictionary |
4 | radiansdict.get(key, default=None) Returns the specified key Value, if the value is not in the dictionary, return the default value |
5 | ##radiansdict.has_key(key)Returns true if the key is in the dictionary dict, otherwise returns false |
radiansdict.items() | Returns a traversable (key, value) tuple array as a list |
radiansdict.keys() | Returns all the keys of a dictionary as a list |
radiansdict.setdefault(key , default=None) | Similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default |
radiansdict.update(dict2) | Update the key/value pairs of dictionary dict2 into dict |
radiansdict.values() | Returns all values in the dictionary as a list |