Python Dictionary operations

Source: Internet
Author: User
This article mainly introduces the detailed operation method of the Python Dictionary (Dictionary). you can refer to the Python Dictionary as another variable container model and store any type of objects, other container models, such as strings, numbers, and tuples.
I. create a dictionary
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:

The code is as follows:

Dict = {'Alice ': '000000', 'Beth': '000000', 'Cecil ': '000000 '}


You can also create a dictionary as follows:

The code is as follows:

Dict1 = {'ABC': 456 };
Dict2 = {'ABC': 123, 98.6: 37 };


Note:
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.
2. access the value in the dictionary
Place the corresponding keys in the familiar square brackets, as shown in the following example:

The code is as follows:

#! /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']: Zara
# Dict ['age']: 7


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

The code is 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 '[/code]
3. modify the dictionary
You can add a new key/value pair to a dictionary to modify or delete an existing key/value pair as follows:

The code is 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 instance:
# Dict ['age']: 8
# Dict ['school ']: DPS School


4. 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:

The code is as follows:

#! /Usr/bin/python

Dict = {'name': 'Zara ', 'age': 7, 'class': 'First '};

Del dict ['name']; # Delete an entry whose key is 'name'
Dict. clear (); # clear all dictionary entries
Del dict; # delete a dictionary

Print "dict ['age']:", dict ['age'];
Print "dict ['school ']:", dict ['school'];
# This causes an exception because the dictionary no longer exists after del:

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


V. features of dictionary keys
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:

The code is 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:

The code is as follows:

#! /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


6. built-in dictionary functions & methods
The Python dictionary contains the following built-in functions:
1. cmp (dict1, dict2): compares two dictionary elements.
2. len (dict): calculates 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 methods:
1. radiansdict. clear (): deletes all elements in the dictionary.
2. radiansdict. copy (): returns the shortest copy of a dictionary.
3. radiansdict. fromkeys (): creates a new dictionary and uses the elements in sequence seq as the dictionary key. val is the initial value corresponding to all keys in the dictionary.
4. radiansdict. get (key, default = None): return 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 is returned in the dictionary dict, false is returned.
6. radiansdict. items (): returns an array of (key, value) tuples that can be traversed in a list.
7. radiansdict. keys (): returns all keys of a dictionary in a list.
8. radiansdict. setdefault (key, default = None): Similar to get (). However, 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 pair to dict.
10. radiansdict. values (): returns all values in the dictionary in a list.

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.