Python tutorial python dictionary (Dictionary)

Source: Internet
Author: User

Python Dictionary (Dictionary)

A dictionary is another mutable container model, and can store any type of object, such as another container model.

A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:

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

You can also create a dictionary like this:

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

Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).

The key must be unique, but the value does not have to be.

The value can take any data type, but it must be immutable, such as a string, number, or tuple.

Accessing values in the dictionary

Put the corresponding key into the familiar square brackets, the following example:

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

The result of the above example output:

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

If the data is accessed using a key that is not in the dictionary, the output error is as follows:

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

The result of the above example output:

dict[' Zara ']:traceback (most recent):  File "test.py", line 4, <module>    print "dict[' Alice ']:" , dict[' Alice '; Keyerror: ' Alice '

Modify Dictionary

The way to add new content to a dictionary is to add a new key/value pair, 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 '];p rint "dict[' School ']:", dict[' School '];

The result of the above example output:

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

Delete a dictionary element

The ability to delete a single element also clears the dictionary, emptying only one operation.

Show Delete a dictionary with the Del command, as in the following example:

#!/usr/bin/python dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '}; Del dict[' Name ']; # Delete key is ' Name ' entry dict.clear ();     # Empty dictionary all Entries del dict;        # Delete the dictionary print "dict[' age ']:", dict[' age '];p rint "dict[' School ']:", dict[' School '];

However, this throws an exception because the dictionary no longer exists after Del:

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

Note: The Del () method is also discussed later.

Delete a dictionary element

Properties of Dictionary Keys

A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.

Two important points to keep in mind:


1) The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following instance

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

The result of the above example output:

dict[' Name ']:  Manni

2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:

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

The result of the above example output:

Traceback (most recent):  File "test.py", line 3, <module>    dict = {[' Name ']: ' Zara ', ' age ': 7};t Ypeerror:list Objects is 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)
Calculates the number of dictionary elements, that is, the total number of keys.

3 Str (DICT)
The output dictionary is a printable string representation.

4 Type (variable)
Returns the type of the variable entered and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in functions:

Serial number

Functions and descriptions

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

2 radiansdict.copy ()
Returns a shallow copy of a dictionary

3 Radiansdict.fromkeys ()
Create a new dictionary with the keys to the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary

4 Radiansdict.get (key, Default=none)
Returns the value of the specified key if the value does not return the default value in the dictionary

5 Radiansdict.has_key (Key)
Returns False if the key returns true in the dictionary Dict

6 Radiansdict.items ()
Returns an array of traversed (key, value) tuples as a list

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

8 Radiansdict.setdefault (key, Default=none)
Similar to get (), but if the key does not already exist in the dictionary, the key will be added and the value will be set to default

9 Radiansdict.update (DICT2)
Update the key/value pairs of the dictionary dict2 to the Dict

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

The above is the "Python Tutorial" python Dictionary (Dictionary) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.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.