Example summary of the dictionary dict common operation methods in python

  • 2020-05-05 11:26:49
  • OfStack

This example summarizes the common operations of dictionary dict in python. Share with you for your reference. The details are as follows:

The python code below shows the common operations of dictionaries in python. Dictionaries play an important role in the development of python


# Create an empty dictionary 
x = {}
# Create a dictionary with three items 
x = {"one":1, "two":2, "three":3}
# Access one of these elements 
x['two']
# Returns a list of all keys in the dictionary 
x.keys()
# Returns a 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 item 
del x["four"]
# Copy a dictionary to the new variable 
y = x.copy()
# Clear all dictionary items 
x.clear()
# Returns the dictionary length and number of items 
z = len(x)
# Detects whether the dictionary contains the specified key
z = x.has_key("one")
# Go through the dictionary key
for item in x.keys(): print item
# Traverses the list of values in the dictionary 
for item in x.values(): print item
# use if Statement gets 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 has been helpful to your Python programming.


Related articles: