This article describes a collection of practical operations such as dictionary creation, traversal, and addition in Python, this article describes the list of common dictionary methods, the five methods for creating a dictionary, and the methods for traversing the dictionary's key values, for more information, see the following field: Python is the only key-value type in the dictionary. it is a very important data structure in Python. it stores data in hash mode, the complexity is O (1), and the speed is very fast. The following lists the common usage of dictionaries.
I. list of common dictionary methods
The code is as follows:
# Method # Description
Bytes -------------------------------------------------------------------------------------------------
D. clear () # remove all items in D
D. copy () # returns a copy of D.
D. fromkeys (seq [, val]) # returns the Dictionary of keys obtained from seq and values set to val. Class method call
D. get (key [, default]) # if D [key] exists, return it; otherwise, return the given default value None.
D. has_key (key) # check whether D has a given key.
D. items () # return the list of (key, value) pairs that represent item D.
D. iteritems () # return an iteratable object from the (key, value) pair returned by D. items ()
D. iterkeys () # return an iteratable object from the D key
D. itervalues () # return an iteratable object from the value of D.
D. keys () # returns the list of keys D.
D. pop (key [, d]) # Remove and return the value corresponding to the given key or the given default value D.
D. popitem () # remove any item from D and use it as a (key, value) pair to return
D. setdefault (key [, default]) # if D [key] exists, return it; otherwise, return the default value None.
D. update (other) # Add each item in other to D.
D. values () # returns the list of values in D.
2. five ways to create a dictionary
Method 1: General method
The code is as follows:
# This method is more convenient if you can spell out the entire dictionary in advance
>>> D1 = {'name': 'Bob', 'age': 40}
Method 2: dynamic creation
The code is as follows:
# This method is convenient if you need to dynamically create a dictionary field
>>> D2 = {}
>>> D2 ['name'] = 'Bob'
>>> D2 ['age'] = 40
>>> D2
{'Age': 40, 'name': 'Bob '}
Method 3: dict-keyword form
The code is as follows:
# The code is relatively small, but the key must be of the string type. Used for function assignment
>>> D3 = dict (name = 'Bob', age = 45)
>>> D3
{'Age': 45, 'name': 'Bob '}
Method 4: dict-key-value sequence
The code is as follows:
# This method is useful if you need to gradually build a sequence of key values, which is often used together with the zip function
>>> D4 = dict ([('name', 'Bob'), ('age', 40)])
>>> D4
{'Age': 40, 'name': 'Bob '}
Or
The code is as follows:
>>> D = dict (zip ('name', 'Bob'), ('age', 40 )))
>>> D
{'Bob': 40, 'name': 'age '}
Method 5: dict -- fromkeys method # It is better to use this method if the key values are the same, and fromkeys can be used for initialization.
The code is as follows:
>>> D5 = dict. fromkeys (['A', 'B'], 0)
>>> D5
{'A': 0, 'B': 0}
If the key value is not provided, the default value is None.
The code is as follows:
>>> D3 = dict. fromkeys (['A', 'B'])
>>> D3
{'A': None, 'B': None}
III. dictionary-type key-value traversal method
The code is as follows:
>>> D = {'X': 1, 'y': 2, 'Z': 3} # Method 1
>>> For key in D:
Print key, '=>', D [key]
Y => 2
X => 1
Z => 3
>>> For key, value in D. items (): # Method 2
Print key, '=>', value
Y => 2
X => 1
Z => 3
>>> For key in D. iterkeys (): # method 3
Print key, '=>', D [key]
Y => 2
X => 1
Z => 3
>>> For value in D. values (): # Method 4
Print value
2
1
3
>>> For key, value in D. iteritems (): # method 5
Print key, '=>', value
Y => 2
X => 1
Z => 3
Note: Using D. iteritems (), D. iterkeys () is much faster than without iter.
4. switch is replaced by one of the common functions of the dictionary.
In C/C ++/Java, there is a convenient function switch, for example:
The code is as follows:
Public class test {
Public static void main (String [] args ){
String s = "C ";
Switch (s ){
Case "":
System. out. println ("");
Break;
Case "B ":
System. out. println ("B ");
Break;
Case "C ":
System. out. println ("C ");
Break;
Default:
System. out. println ("D ");
}
}
}
To implement the same function in Python,
Method 1 is implemented using the if and else statements, for example:
The code is as follows:
From _ future _ import pision
Def add (x, y ):
Return x + y
Def sub (x, y ):
Return x-y
Def mul (x, y ):
Return x * y
Def p (x, y ):
Return x/y
Def operator (x, y, sep = '+ '):
If sep = '+': print add (x, y)
Elif sep = '-': print sub (x, y)
Elif sep = '*': print mul (x, y)
Elif sep = '/': print p (x, y)
Else: print 'something Wrong'
Print _ name __
If _ name _ = '_ main __':
X = int (raw_input ("Enter the 1st number :"))
Y = int (raw_input ("Enter the 2nd number :"))
S = raw_input ("Enter operation here (+ -*/):")
Operator (x, y, s)
Method 2: use a dictionary to skillfully implement the same switch function, for example:
The code is as follows:
# Coding = gbk
From _ future _ import pision
X = int (raw_input ("Enter the 1st number :"))
Y = int (raw_input ("Enter the 2nd number :"))
Def operator (o ):
Dict_rows = {
'+': Lambda x, y: x + y,
'-': Lambda x, y: x-y,
'*': Lambda x, y: x * y,
'/': Lambda x, y: x/y}
Return dict_oper.get (o) (x, y)
If _ name _ = '_ main __':
O = raw_input ("Enter operation here (+ -*/):")
Print operator (o)