Python dictionary operations

Source: Internet
Author: User
A dictionary is the most flexible built-in data structure in python, and a dictionary is an unordered set (the dictionary is randomly ordered for fast key search execution). python uses the optimal hash algorithm to find keys; the dictionary is similar to map in java, but it does not have as many types (such as HashMap and TreeMap) as map in java ).

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

A dictionary is the most flexible built-in data structure in python, and a dictionary is an unordered set (the dictionary is randomly ordered for fast key search execution). python uses the optimal hash algorithm to find keys; the dictionary is similar to map in java, but it does not have as many types (such as HashMap and TreeMap) as map 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

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.