How to get started with the Python dictionary

Source: Internet
Author: User
Tags delete key shallow copy

This article mainly introduces the Python dictionary (Dictionary) of the detailed operation method, the need for friends can refer to the following:

A python dictionary is another mutable container model, and can store any type of object, such as strings, numbers, tuples, and other container models.

First, create a dictionary
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

' ABC ': 456'abc': 123, 98.6:37};

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

Second, access the values in the dictionary
Put the corresponding key into the familiar square brackets, the following example:

#!/usr/bin/pythonDict= {'Name':'Zara',' Age': 7,'Class':' First'};Print "dict[' Name ']:", dict['Name'];Print "dict[' age ']:", dict[' Age'];#The result of the above example output:#dict[' Name ': Zara#dict[' age ': 7

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

#!/usr/bin/pythonDict= {'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, in <module>#    print "dict[' Alice ']:", dict[' Alice ' ]; # keyerror: ' Alice ' [/code]

Third, modify the 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/pythonDict= {'Name':'Zara',' Age': 7,'Class':' First'};d ict[' Age'] = 8;#Update Existing entrydict['School'] ="DPS School";#ADD new Entry Print "dict[' age ']:", dict[' Age'];Print "dict[' School ']:", dict['School'];#The result of the above example output:#dict[' age ': 8#dict[' School ': DPS School

Iv. Deleting 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/pythonDict= {'Name':'Zara',' Age': 7,'Class':' First'};deldict['Name'];#Delete key is ' Name ' entryDict.clear ();#Empty dictionary all entriesdelDict;#Delete DictionaryPrint "dict[' age ']:", dict[' Age'];Print "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, <module>#print "dict[' age '):", dict[' age ');#TypeError: ' Type ' object is unsubscriptable

V. Characteristics 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 example:

#!/usr/bin/pythonDict= {'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/pythonDict= {['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};#typeerror:list objects is unhashable

Six, dictionary built-in functions & methods
The Python dictionary contains the following built-in functions:
1, CMP (Dict1, DICT2): compare 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): Returns the type of the input variable and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in methods:
1, Radiansdict.clear (): Delete all elements in the dictionary
2, Radiansdict.copy (): Returns a shallow copy of a dictionary
3. Radiansdict.fromkeys (): Create a new dictionary with the key of 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): If the key in the dictionary dict returns True, otherwise returns false
6, Radiansdict.items (): Returns a traversed (key, value) tuple array in 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): The dictionary dict2 key/value pairs updated to Dict
10. Radiansdict.values (): Returns all values in the dictionary as a list

Reference: http://www.jb51.net/article/47990.htm

How to get started with the Python dictionary

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.