A preliminary introduction to the basic knowledge of dictionaries in Python

Source: Internet
Author: User
Dictionaries are mutable and can store any number of Python objects, including another container type. A dictionary includes key pairs (called items) and their corresponding values.

The Python dictionary is also known as an associative array or hash table. The general syntax of a dictionary is as follows:

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

You can create a dictionary in the following ways:

Dict1 = {' abc ': 456};d ict2 = {' abc ': 123, 98.6:37};

Each key comes from its value with a colon (:), the item is separated by commas, and the whole thing is enclosed in curly braces. Without any items an empty dictionary is written with only two curly braces, just like this: {}

The key is unique in a dictionary, and the value may not be. The value of the dictionary can be of any type, but the keys must be immutable data types, such as strings, numbers, or tuples.
To access the value of the dictionary:

To access the dictionary element, you can use the familiar square brackets together with the key to get its value. The following is a simple example:

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First '};p rint ' dict[' name ']: ", dict[' name '];p rint" dict[' Ag E ']: ", dict[' age ');

When executing the above code, the following results are produced:

dict[' Name ': zaradict[' age ': 7

If you want to access a nonexistent key, this gets an error, as follows:

#!/usr/bin/pythondict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};p rint ' dict[' Alice ']: ", dict[' Alice ');

When the above code is executed, the following results are produced:

dict[' Zara ']:traceback (most recent): File "test.py", line 4, in 
 
  
   
    print "dict[' Alice ']:", dict[' Ali Ce ']; Keyerror: ' Alice '
 
  

Update Dictionary:

You can modify an existing entry or delete it by adding a new entry or item (that is, a key-value pair). As a simple example, update the words in the existing entries as shown:

#!/usr/bin/pythondict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};d ict[' age ' = 8; # Update existing entrydict[' School '] = "DPS School"; # ADD New Entryprint "dict[' age '):", dict[' age '];p rint "dict[' School ']:", dict[' School '];

When the above code is executed, the following results are produced:

Dict[' age ': 8dict[' School ': DPS School

To delete a dictionary element:

You can delete a single dictionary element or clear everything in the dictionary. You can also delete the entire dictionary in a single operation.

To delete the entire dictionary, simply use the DEL statement. The following is a simple example:

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First '};d el dict[' name ']; # Remove entry with key ' Name ' dict.clear ();   # Remove all entries in Dictdel dict;    # delete entire Dictionaryprint "dict[' age '):" dict[' age '];p rint "dict[' School ']:", dict[' School '];

This will produce the following results. Note that the exception is thrown because the dictionary does not already exist after Del dict deletion:

dict[' age ']:traceback (most recent): File "test.py", line 8, in 
 
  
   
    print "dict[' age ']:", dict[' age '); TypeError: ' Type ' object is unsubscriptable
 
  

Note: The Del () method is discussed in the following sections.
The properties of the dictionary key:

There is no limit to the dictionary value. They can be any Python object, whether it is a standard object or a user-defined object. But as a key, it is not possible.

To remember the two main points of a key in a dictionary:

(a) Do not allow a key to correspond to multiple entries. This means that you cannot have duplicate keys. When there are duplicate keys, the allocation process is based on the last assignment. The following is a simple example:

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '};p rint ' dict[' name ']: ", dict[' name '];

When the above code is executed, the following results are produced:

dict[' Name ']: Manni

(b) The value word of the key must be immutable. This means that strings, numbers, or tuples can be used as keys to the dictionary, but such as [' key '] is not allowed. The following is a simple example:

#!/usr/bin/pythondict = {[' name ']: ' Zara ', ' Age ': 7};p rint ' dict[' name ']: ", dict[' name '];

When the above code is executed, the following results are produced:

Traceback (most recent): File "test.py", line 3, in 
 
  
   
    dict = {[' Name ']: ' Zara ', ' Age ': 7}; Typeerror:list objects is unhashable
 
  
  • 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.