Python Dictionary Operations

Source: Internet
Author: User

Today, I'm going to write something every week to keep track of my study, mark.

The dictionary is the most flexible built-in data structure in Python, dictionaries are unordered collections (the order of the dictionaries is random for fast key lookups), Python uses the most optimized hashing algorithm to find keys; Dictionaries are similar to maps in Java, but there are not many types of maps in Java (HashMap , TreeMap, etc.).

Common dictionary Operations

Assign value

D = {}  # empty dictionary d = {"name": "Zhangsan", "Age":  # 2 Items Dictionary d = {"Fruit": {"Apple": 2, "Orange": 1}}  # nested d = di Ct.fromkeys (["A", "B"], 2)  # {' A ': 2, ' B ': 2}d = Dict (["Name", "Age"], ["Zhangsan", ' "[]]")  # {' Age ': ' + ', ' n ' Ame ': ' Zhangsan '}

Take value

Name = d["name"]age = D.get ("Age", 0)  # If the age attribute is not present, the value is 0keys = D.keys ()  # gets the key values = D.values ()  # get Valueif ' n Ame ' in D:    print ' name was in d '

Delete

D.pop (' sex ')  # delete del d[' name ' according to key  # Delete according to 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.