Python dictionary operations and python dictionary operations

Source: Internet
Author: User

Python dictionary operations and python dictionary operations
Today, I plan to write something every week to record my learning and mark it myself.

The dictionary is the most flexible built-in data structure in python. The dictionary isUnordered(The dictionary sequence is random to quickly execute the key search), python uses the optimal hash algorithm to find the key; the dictionary is similar to the map in java, however, there are not as many map types (such as HashMap and TreeMap) in java ).

Common dictionary operations

Assignment

D ={}# empty dictionary D = {"name": "zhangsan", "age": 23} # dictionary D containing two projects = {"fruit ": {"apple": 2, "orange": 1 }}# nested D = dict. fromkeys (["a", "B"], 2) # {'A': 2, 'B': 2} D = dict (zip (["name ", "age"], ["zhangsan", '23']) # {'age': '23', 'name': 'hangsan '}

Value

Name = D ["name"] age = D. get ("age", 0) # If the age attribute does not exist, set the value to 0 keys = D. keys () # obtain the key values = D. values () # obtain valueif 'name' in D: print "name is in D"

Delete

D. pop ('sex') # Delete del D ['name'] by key # Delete by key

Other operations

D_1 = {"sex": "male"} D. update (D_1) # merge dict

Write it here first, and then add it later.

Related Article

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.