Summary of examples of common dict operations in python

Source: Internet
Author: User
This article mainly introduces the common dictionary dict operation methods in python. The example summarizes the dictionary operation skills of Python, which is of great practical value, for more information about how to use the dictionary dict in python, see the examples in this article. Share it with you for your reference. The details are as follows:

The following python code demonstrates the common operations of dictionaries in python. dictionaries play an important role in python development. it is very important to master dictionary operations.

# Create an empty dictionary x ={}# create a dictionary x = {"one": 1, "two": 2, "three ": 3} # access an element x ['two'] # return the list of all keys in the dictionary x. keys () # returns the list of all values in the dictionary x. values () # Add a new project x ["four"] = 4 # Modify a dictionary project x ["one"] = "uno" # delete a dictionary project del x ["four"] # Copy a dictionary to the new variable y = x. copy () # clear all Dictionary items x. clear () # returns the dictionary length. the number of items z = len (x) # checks whether the dictionary contains the specified keyz = x. has_key ("one") # traverse the dictionary's keyfor item in x. keys (): print item # traverse the value list in the dictionary for item in x. values (): print item # Use the if statement to obtain the corresponding key value in the dictionary if "one" in x: print x ['one'] if "two" not in x: print "Two not found" if "three" in x: del x ['Three ']

I hope this article will help you with Python programming.

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.