Python basic in...login
Python basic introductory tutorial
author:php.cn  update time:2022-04-18 16:14:50

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:

d = {key1 : value1, key2 : value2 }

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:

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

You can also create a dictionary like this:

dict1 = { 'abc': 456 };
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:

#!/usr/ bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

Output result of the above example:

dict['Name']: Zara
dict['Age']: 7

If you access data using keys that are not in the dictionary, the following error will be output:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];

The above example output result:

dict['Zara']:
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:

#!/usr/bin/python

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'];
Output result of the above example:
dict[' Age']: 8
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:

#!/usr/bin/python
# -*- 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'];

But this will throw an exception because the dictionary no longer exists after using del:

dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict[' Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

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

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

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict[' Name'];

Output result of the above example:

dict['Name']: Manni

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:

#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age ': 7};

print "dict['Name']: ", dict['Name'];

Output result of the above example:

Traceback (most recent call last):
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 numberFunction and description
1cmp(dict1, dict2)
Compare two Dictionary element.
2len(dict)
Calculate the number of dictionary elements, that is, the total number of keys.
3str(dict)
Output the printable string representation of the dictionary.
4type(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:

##radiansdict.has_key(key)6radiansdict.items()7radiansdict.keys()8radiansdict.setdefault(key , default=None)9radiansdict.update(dict2)10radiansdict.values()
Serial numberFunction and description
1radiansdict.clear()
Delete all elements in the dictionary
2radiansdict .copy()
Returns a shallow copy of the dictionary
3radiansdict.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
4radiansdict.get(key, default=None)
Returns the specified key Value, if the value is not in the dictionary, return the default value
5Returns true if the key is in the dictionary dict, otherwise returns false
Returns a traversable (key, value) tuple array as a list
Returns all the keys of a dictionary as a list
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
Update the key/value pairs of dictionary dict2 into dict
Returns all values ​​in the dictionary as a list