Learn the Python dict () operation method from the old man

Source: Internet
Author: User
This article mainly introduces the operation methods of dict (). Because many methods of dict are similar to those of list, dict is also compared with list, this is a very good article. If you have any need, refer to many methods of dict, which are similar to those of list. Here we will compare them with list.

Nesting

Nested in the list also exists, that is, the element is list. In dict, there are similar styles:

>>> A_list = [[1, 2, 3], [4, 5], [6, 7] >>>> a_list [1] [1] 5 >>> a_dict = {1: {"name": "qiwsir"}, 2: "python", "email": "qiwsir@gmail.com" >>> a_dict {1: {'name ': 'qiwsir '}, 2: 'python', 'email ': 'qiwsir @ gmail.com '} >>> a_dict [1] ['name'] # A nested dict method to access its value: Write the key 'qiwsir' layer by layer'

Obtain keys and values

In the previous lecture, we know that the value can be obtained through the dict key. Example.

Is there any other way to get the key value? Yes! Python generally does not have only one method to implement an operation.

>>> Website = {1: "google", "second": "baidu", 3: "facebook", "twitter": 4 }>>># use d. the keys () method gets all the keys of dict. The result is list >>> website. keys () [1, 'second', 3, 'twitter '] >>> # Use d. the values () method gets all the values of dict. If no dict is nested in it, the result is list >>> website. values () ['Google ', 'baidu', 'Facebook', 4] >>## use items () the result is a list, but the elements in the list are tuples >>> website. items () [(1, 'Google '), ('second', 'baidu'), (3, 'Facebook'), ('twitter ', 4)]

From the above results, we can see that we can also use the for statement to obtain the corresponding content in a loop. For example:

>>> For key in website. keys ():... print key, type (key)... 1
 
  
Second
  
   
3
   
    
Twitter
    
     
>>># The following method is the same as the preceding method >>> for key in website:... print key, type (key)... 1
     
      
Second
      
        3
       
         Twitter
        
       
      
     
    
   
  
 

The following two methods are equivalent:

>>> for value in website.values():...   print value... googlebaidufacebook4>>> for key in website:...   print website[key]... googlebaidufacebook4

The following method is equivalent:

>>> for k,v in website.items():...   print str(k)+":"+str(v)... 1:googlesecond:baidu3:facebooktwitter:4>>> for k in website:...   print str(k)+":"+str(website[k])... 1:googlesecond:baidu3:facebooktwitter:4

The following method can also get the key value, but it seems that you need to press the keyboard more

>>> website{1: 'google', 'second': 'baidu', 3: 'facebook', 'twitter': 4}>>> website.get(1)   'google'>>> website.get("second")'baidu'

Other common methods

The methods in dict are not described too much here, because classes have been listed in the previous section. You can try them one by one if you are interested. The following lists several common

>>> Len (website) 4 >>> website {1: 'Google ', 'second': 'baidu', 3: 'Facebook', 'twitter ': 4 }>>> new_web = website. copy () # copy one copy. This copy is also called a shallow copy, which corresponds to a deep copy. >>> New_web # What is the difference between the two? You can google it. {1: 'Google ', 'second': 'Baidu', 3: 'Facebook ', 'twitter': 4}

There are two methods to delete a key-value pair, but there is a difference between the two.

>>># D. pop (key), delete the corresponding key-Value Pair Based on the key, and return the value >>> new_web.pop ('second ') 'baidu' >>> del new_web [3] # No return value. If the deletion key does not exist, an error is returned >>> new_web {1: 'Google ', 'twitter ': 4 }>>> del new_web [9] Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
KeyError: 9
  
 

D. update (d2) can be used to merge d2 into d.

>>> Cnweb {'qq': 'First in cn', 'python': 'qiwsir. github. io ', 'alibaba': 'business' }>>> website {1: 'Google', 'second': 'Baidu ', 3: 'Facebook', 'twitter ': 4 }>>> website. update (cnweb) # merge cnweb into website> website # changed {'qq': 'First in cn', 1: 'Google ', 'second ': 'baidu', 3: 'Facebook ', 'python': 'qiwsir. github. io ', 'twitter': 4, 'alibaba': 'business' }>>> cnweb # not changed {'qq': 'First in cn', 'python ': 'qiwsir. github. io ', 'alibaba': 'business '}

At the end of this lecture, I would like to remind the readers that in python3, dict has many changes. For example, it is very interesting to be able to perform dictionary resolution, just like list resolution.

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.