Python Dictionary (Dictionary) operations detailed _python

Source: Internet
Author: User
Tags delete key shallow copy

The Python dictionary is another variable container model, and can store any type of object, such as strings, numbers, tuples, and other container models.
First, create a dictionary
The 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:

Copy Code code as follows:
Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}

You can also create a dictionary like this:
Copy Code code as follows:
Dict1 = {' abc ': 456};
Dict2 = {' abc ': 123, 98.6:37};

Attention:
Each key is separated from the value by a colon (:), each pair is separated by commas, and the whole is enclosed in curly braces ({}).
The key must be unique, but the value is not necessary.
Values can take any data type, but must be immutable, such as strings, numbers, or tuples.
second, access to the dictionary value
Put the corresponding key into the familiar square bracket, the following example:
Copy Code code as follows:
#!/usr/bin/python

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

print "dict[' name ']:", dict[' name ';
Print "dict[' age ']:", dict[' age ';
#以上实例输出结果:

#dict [' Name ']: Zara
#dict [' Age ']: 7


If you use a key that is not in the dictionary to access the data, the error is printed as follows:
Copy Code code as follows:
#!/usr/bin/python

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

Print "dict[' Alice ']:", dict[' Alice '];

#以上实例输出结果:

#dict [' Zara ']:
#Traceback (most recent call last):
# File "test.py", line 4, in <module>
# print "dict[' Alice ']:", dict[' Alice '];
#KeyError: ' Alice ' [/code]
Iii. Modifying the Dictionary
The way to add new content to a dictionary is to add new key/value pairs, modify or delete existing key/value pairs as follows:

Copy Code code as follows:
#!/usr/bin/python

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

dict[' age ' = 8; # Update Existing entry
dict[' School ' = "DPS School"; # ADD New Entry


Print "dict[' age ']:", dict[' age ';
Print "dict[' School ']:", dict[' School '];
#以上实例输出结果:
#dict [' Age ']: 8
#dict [' School ']: DPS School

Iv. Delete dictionary elements
Can delete a single element can also empty the dictionary, empty only one operation.
Display deletes a dictionary with the DEL command, as follows:
Copy Code code as follows:
#!/usr/bin/python

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

Del dict[' Name ']; # Delete key is ' Name ' entry
Dict.clear (); # Empty Dictionary all entries
Del Dict; # Delete Dictionary

Print "dict[' age ']:", dict[' age ';
Print "dict[' School ']:", dict[' School '];
#但这会引发一个异常 because the dictionary no longer exists with Del:

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


characteristics of dictionary keys
Dictionary values can be used without restrictions on any Python object, either as a standard object or as a user-defined, but not a key.
Two important points to remember:
1 does not allow the same key to appear two times. When created, if the same key is assigned two times, the latter value is remembered, as in the following example:
Copy Code code as follows:
#!/usr/bin/python

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

print "dict[' name ']:", dict[' name ';
#以上实例输出结果:
#dict [' Name ']: Manni

2 The key must be immutable, so you can use a number, a string or a tuple to act, so use the list is not, the following example:
Copy Code code as follows:
#!/usr/bin/python

Dict = {[' Name ']: ' Zara ', ' Age ': 7};

print "dict[' name ']:", dict[' name ';
#以上实例输出结果:

#Traceback (most recent call last):
# File "test.py", line 3, in <module>
# dict = {[' Name ']: ' Zara ', ' Age ': 7};
#TypeError: List objects are unhashable


Vi. 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): Calculate 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 variable entered, 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 the elements in the dictionary
2. Radiansdict.copy (): Returns a shallow copy of a dictionary
3, Radiansdict.fromkeys (): Create a new dictionary, in the sequence of the elements in Seq Dictionary key, Val for the dictionary all keys corresponding to the initial value
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 return false
6, Radiansdict.items (): To return a list of iterated (key, value) tuple array
7, Radiansdict.keys (): Return a dictionary with a list of all the keys
8, Radiansdict.setdefault (Key, Default=none): and get () similar, but if the key does not already exist in the dictionary, will add the key and set the value to default
9. Radiansdict.update (DICT2): Update the dictionary dict2 key/value pairs into dict
10, Radiansdict.values (): Returns all the values in the dictionary with the 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.