[Python Tutorial] Python Dictionary (Dictionary)

Source: Internet
Author: User
A dictionary is another variable container model that can store any type of objects, such as other container models.

Python Dictionary)

A dictionary is another variable container model that can store any type of objects, such as other container models.

The dictionary is composed of key pairs and corresponding values. A dictionary is also called an associated array or a hash table. The basic syntax is as follows:

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

You can also create a dictionary as follows:

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

Each key and value are separated by a colon (:). each pair is separated by a comma. each pair is separated by a comma and placed in curly brackets ({}).

The key must be unique, but the value is not required.

Values can be of any data type, but must be immutable, such as strings, numbers, or tuples.

Value in the access Dictionary

Place the corresponding keys in the familiar square brackets, as shown 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 instance:

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

If you use a key that is not in the dictionary to access data, an error is returned as follows:

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

Output result of the above instance:

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

Modify Dictionary

You can add a new key/value pair to a dictionary to modify or delete an existing key/value pair as follows:

#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8; # update existing entrydict['School'] = "DPS School"; # Add new entry  print "dict['Age']: ", dict['Age'];print "dict['School']: ", dict['School'];

Output result of the above instance:

dict['Age']:  8dict['School']:  DPS School

Delete dictionary elements

Only one operation is required to delete a single element and clear the dictionary.

The following example shows how to delete a dictionary using the del command:

#! /Usr/bin/python dict = {'name': 'Zara ', 'age': 7, 'class': 'first'}; del dict ['name']; # Delete the dict entry whose key is 'name. clear (); # clear all dictionary entries del dict; # Delete the dictionary print "dict ['age']:", dict ['age']; print "dict ['school ']:", dict ['school'];

However, this causes an exception because the dictionary after del is used does not exist:

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

Note: The del () method will be discussed later.

Delete dictionary elements

Dictionary key features

Dictionary values can be any python object without restrictions. they can be either standard objects or user-defined objects, but cannot be keys.

There are two important points to remember:


1) the same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered as follows:

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

Output result of the above instance:

dict['Name']:  Manni

2) the key must be unchangeable. Therefore, you can use numbers, strings, or tuples to act as the key. Therefore, you cannot use the list, as shown in the following example:

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

Output result of the above instance:

Traceback (most recent call last):  File "test.py", line 3, in 
 
      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

Functions and descriptions

1 cmp (dict1, dict2)
Compares two dictionary elements.

2 len (dict)
Calculate the number of dictionary elements, that is, the total number of keys.

3 str (dict)
Output dictionary printable string representation.

4 type (variable)
Return the input variable type. if the variable is a dictionary, the dictionary type is returned.

The Python dictionary contains the following built-in functions:

Serial Number

Functions and descriptions

1 radiansdict. clear ()
Delete all elements in the dictionary

2 radiansdict. copy ()
Returns the shortest copy of a dictionary.

3 radiansdict. fromkeys ()
Create a new dictionary and use the elements in sequence seq as the dictionary key. val is the initial value corresponding to all the keys in the dictionary.

4 radiansdict. get (key, default = None)
Returns the value of the specified key. if the value is not in the dictionary, the default value is returned.

5 radiansdict. has_key (key)
If the key returns true in the dictionary dict, otherwise false is returned.

6 radiansdict. items ()
Returns a list of traversal (key, value) tuples.

7 radiansdict. keys ()
Returns all keys of a dictionary in a list.

8 radiansdict. setdefault (key, default = None)
Similar to get (), but if the key does not exist in the dictionary, a key is added and the value is set to default.

9 radiansdict. update (dict2)
Update the dictionary dict2 key/value pairs to dict.

10 radiansdict. values ()
Returns all values in the dictionary as a list.

The above is the content of the [python Tutorial] Python Dictionary (Dictionary). For more information, see PHP Chinese network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.