Summary of common operations on the python dictionary

Source: Internet
Author: User
The following is a summary of common operations on the python dictionary. I think this is quite good. Now I will share it with you and give you a reference. Let's take a look at the Python dictionary as another variable container model (unordered ), it can store any type of objects, such as strings, numbers, tuples, and other container models. This article describes how to use the dictionary (Dict) in Python, including creating, accessing, deleting, and other operations. For more information, see.

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:

1. Create a dictionary

>>> Dict = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3': 'printer '} tip: The dictionary contains a list: dict = {'yangrong ': ['23', 'it'], "xiaohei": ['22', 'dota']} contains a dictionary: dict = {'yangrong ': {"age": "23", "job": "IT"}, "xiaohei": {"'age': '22 ', 'job': 'dota '"} Note: each key and value are separated by a colon (:), and each pair is separated by a comma, in curly braces ({}). The key must be unique, but the value is not required.

2. Access the value in the dictionary

>>> Dict = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3 ': 'printer' }>> print (dict ['ob1']) if the computer uses a key that is not in the dictionary to access data, an error is returned as follows: >>> print (dict ['ob4']) Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
Print (dict ['ob4']) access all values >>> dict1 = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3 ': 'printer' }>>> for key in dict1: print (key, dict1 [key]) ob3 printerob2 mouseob1 computer
  
 

3. Modify the dictionary

>>> dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}>>> dict['ob1']='book'>>> print(dict){'ob3': 'printer', 'ob2': 'mouse', 'ob1': 'book'}

4. delete a dictionary

Can delete a single element >>> dict = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3 ': 'printer' }>>> del dict ['ob1'] >>> print (dict) {'ob3': 'printer', 'ob2 ': 'mouse '} Delete all elements in the dictionary >>> dict1 = {'ob1': 'computer', 'ob2': 'mouse ', 'ob1 ': 'printer' >>>> dict1.clear () >>>> print (dict1) {} deletes the entire dictionary. An exception is thrown when you access the dictionary after deletion. >> Dict1 = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3': 'printer '} >>> del dict1 >>> print (dict1) traceback (most recent call last): File"
 
  
", Line 1, in
  
   
Print (dict1) NameError: name 'dict1' is not defined
  
 

5. Update the dictionary

The update () method can be used to add the content of a dictionary to another dictionary: >>> dict1 = {'ob1': 'computer ', 'ob2 ': 'mouse '}>>> dict2 = {'ob3': 'printer' }>>> dict1.update (dict2) >>>> print (dict1) {'ob3 ': 'printer', 'ob2': 'mouse ', 'ob1': 'computer '}

6. functions related to the ing type

>>> dict(x=1, y=2) {'y': 2, 'x': 1} >>> dict8 = dict(x=1, y=2) >>> dict8 {'y': 2, 'x': 1} >>> dict9 = dict(**dict8) >>> dict9 {'y': 2, 'x': 1}  dict9 = dict8.copy()

7. 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. Two important points must be remembered: 1) the same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered> dict1 = {'ob1': 'computer ', 'ob2': 'mouse ', 'ob1': 'printer '} >>> print (dict1) {'ob2': 'mouse', 'ob1': 'printer '} 2) The key must be unchangeable, therefore, you can use numbers, strings, or tuples. If you use a list, you cannot use them. >>> dict1 = {['ob1']: 'computer ', 'ob2': 'mouse ', 'ob3': 'printer'} Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
Dict1 = {['ob1']: 'computer ', 'ob2': 'mouse', 'ob3': 'printer '} TypeError: unhashable type: 'LIST'
  
 

8. built-in dictionary Functions & Methods

The Python dictionary contains the following built-in functions: 1. cmp (dict1, dict2): Compares two dictionary elements. (Unavailable after python3) 2. len (dict): calculates the number of dictionary elements, that is, the total number of keys. 3. str (dict): Output dictionary printable strings. 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 (): delete all elements in the dictionary. 2. radiansdict. copy (): returns the shortest copies of a dictionary. 3. radiansdict. fromkeys (): Create a new dictionary, which uses the elements in sequence seq as the dictionary key. val is the initial values of all dictionary keys. 4. radiansdict. get (key, default = None): returns the value of the specified key. If the value is not in the dictionary, the default values 5 and radiansdict are returned. has_key (key): If the key returns true in the dictionary dict, otherwise false6 and radiansdict are returned. items (): returns a list of traversal (Key, value) tuples array 7, radiansdict. keys (): returns all keys of a dictionary in a list. setdefault (key, default = None): similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default9 and radiansdict. update (dict2): update the key/value pairs of the dictionary dict2 to dict 10 and radiansdict. values (): returns all values in the dictionary in a list.

The summary of the common operations of the above python dictionary is a summary of all the content that I have shared with you. I hope you can give us a reference and support for me.

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.