Latest web development tutorials

Python dictionary (Dictionary)

Another variable is the dictionary container model, and can store any type of object.

Each dictionary key (key => value) of the colon(:) divided between each pair with a comma (,)division, including the entire dictionary in curly braces({}),the format is as follows:

d = {key1 : value1, key2 : value2 }

Key must be unique, but the value is not necessary.

Value can take any data type, but the key must be immutable, such as strings, numbers, or tuples.

A simple dictionary Example:

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

So also create the dictionary:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Access the dictionary values

The corresponding key in the familiar square brackets following examples:

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

Examples of the above output:

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

If there is no key to access the data dictionary, it will output the following error:

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

Examples of the above output:

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


Modifying a dictionary

Way to add new content to the dictionary to add new key / value pairs, modify or delete existing key / value pairs following examples:

#!/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'];
Examples of the above output:
dict['Age']:  8
dict['School']:  DPS School


Delete dictionary elements

Can delete a single element can be empty dictionary, emptied just one operation.

To delete a dictionary with the del command, the following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典
 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

But this raises an exception, because After del dictionaries no longer exists:

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: The next del () method will be discussed.


Characteristics of the dictionary key

Dictionary values ​​can be taken without limitation, any python object can be both standard object, it can be user-defined, but the key does not work.

Two important points to remember:

1) does not allow the same key appears twice. When you create is assigned if the same key twice, the latter value will be remembered, the following examples:

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

Examples of the above output:

dict['Name']:  Manni

2) key must not be changed, so you can use numeric, string, or tuple to act as, a list will not do so with the following examples:

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

Examples of the above output:

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

Python dictionary contains the following built-in functions:

No. Function and description
1 cmp (dict1, dict2)
Compare two elements in the dictionary.
2 len (dict)
Counting the number of dictionary elements, namely the total number of keys.
3 str (dict)
Printable string output representation of the dictionary.
4 type (variable)
Returns the type of input variable, if the variable is a dictionary returns a dictionary.

Python dictionary contains the following built-in method:

No. Function and description
1 radiansdict.clear ()
Delete all the elements in the dictionary
2 radiansdict.copy ()
Returns a shallow copy of dictionary
3 radiansdict.fromkeys ()
Create a new dictionary to the sequence seq elements do dictionary key, val as a dictionary of all the key corresponding to the initial value
4 radiansdict.get (key, default = None)
Returns the value of the specified key, if the return value is not in the dictionary default values
5 radiansdict.has_key (key)
Returns true if the key is in the dictionary dict, otherwise returns false
6 radiansdict.items ()
Returns a list traversal (key, value) tuples array
7 radiansdict.keys ()
To return a list of all the keys dictionary
8 radiansdict.setdefault (key, default = None)
And get () is similar, but if the key does not exist in the dictionary, and will add value to default keys
9 radiansdict.update (dict2)
Dict2 the dictionary of key / value pairs in the update to the dict
10 radiansdict.values ()
To return a list of all the values ​​in the dictionary