Examples of common dict operations in python, pythondict
This example summarizes the common operations for dictionary dict in python. 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.