The field is Python is the only key-value type in the dictionary, and is a very important data structure in Python, because it stores data in a hash, with a complexity of O (1), which is very fast. The common uses of dictionaries are listed below.
A list of common methods in a dictionary
The code is as follows:
#方法 #描述
-------------------------------------------------------------------------------------------------
D.clear () #移除D中的所有项
D.copy () #返回D的副本
D.fromkeys (Seq[,val]) #返回从seq中获得的键和被设置为val的值的字典. Can do class method call
D.get (Key[,default]) #如果D [key] exists and returns the given default value of None
D.has_key (Key) #检查D是否有给定键key
D.items () #返回表示D项的 (key, value) pairs list
D.iteritems () #从D. Items () Returns an object that can be iterated in the (key, value) pair
D.iterkeys () #从D的键中返回一个可迭代对象
D.itervalues () #从D的值中返回一个可迭代对象
D.keys () #返回D键的列表
D.pop (Key[,d]) #移除并且返回对应给定键key或给定的默认值D的值
D.popitem () #从D中移除任意一项, and use it as a (key, value) pair to return
D.setdefault (Key[,default]) #如果D [key] exists and returns the default value of None
D.update (Other) #将other中的每一项加入到D中.
D.values () #返回D中值的列表
Two, five ways to create a dictionary
Method One: Conventional methods
The code is as follows:
# If you can spell the whole dictionary beforehand, this method is more convenient
>>> D1 = {' name ': ' Bob ', ' Age ': 40}
Method Two: Dynamically create
The code is as follows:
# If you need to dynamically create a field for a dictionary, this method is easier
>>> D2 = {}
>>> d2[' name ' = ' Bob '
>>> d2[' age ' = 40
>>> D2
{' Age ':, ' name ': ' Bob '}
Method Three: dict--keyword form
The code is as follows:
# code is relatively small, but the key must be a string type. Commonly used for function assignment
>>> D3 = dict (name= ' Bob ', age=45)
>>> D3
{' Age ':, ' name ': ' Bob '}
Method four: dict--sequence of key values
The code is as follows:
# This is useful if you need to step through the sequence of key values, often used with the zip function
>>> D4 = dict ([' Name ', ' Bob '], (' Age ', 40)]
>>> D4
{' Age ':, ' name ': ' Bob '}
Or
The code is as follows:
>>> D = dict (Zip (' name ', ' Bob '), (' Age ', 40))
>>> D
{' Bob ':, ' name ': ' Age '}
Method Five: Dict--fromkeys method # If the value of the key is the same, it is better in this way and can be initialized with Fromkeys
The code is as follows:
>>> D5 = Dict.fromkeys ([' A ', ' B '],0)
>>> D5
{' A ': 0, ' B ': 0}
If the value of the key is not provided, the default is None
The code is as follows:
>>> D3 = Dict.fromkeys ([' A ', ' B '])
>>> D3
{' A ': None, ' B ': none}
Key-value traversal methods in dictionaries
The code is as follows:
>>> D = {' x ': 1, ' Y ': 2, ' Z ': 3} # Method One
>>> for key in D:
Print key, ' => ', D[key]
Y => 2
X => 1
Z => 3
>>> for key, value in D.items (): # Method Two
Print key, ' => ', value
Y => 2
X => 1
Z => 3
>>> for key in D.iterkeys (): # Method Three
Print key, ' => ', D[key]
Y => 2
X => 1
Z => 3
>>> for value in D.values (): # method Four
Print value
2
1
3
>>> for key, value in D.iteritems (): # method Five
Print key, ' => ', value
Y => 2
X => 1
Z => 3
Note: The D.iteritems (), D.iterkeys () method is much faster than without ITER.
One of the common uses of dictionaries instead of switch
In the C/c++/java language, there is a convenient function switch, such as:
The code is as follows:
public class Test {
public static void Main (string[] args) {
String s = "C";
Switch (s) {
Case "A":
System.out.println ("A");
Break
Case "B":
System.out.println ("B");
Break
Case "C":
System.out.println ("C");
Break
Default
System.out.println ("D");
}
}
}
To achieve the same function in Python,
Method One, is to use if, else statement to implement, such as:
The code is as follows:
From __future__ Import Division
def add (x, y):
return x + y
def sub (x, y):
return x-y
def mul (x, y):
return x * y
def div (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 div (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 Two, use a dictionary to skillfully implement the same switch functions, such as:
The code is as follows:
#coding =GBK
From __future__ Import Division
x = Int (raw_input ("Enter the 1st Number:"))
y = Int (raw_input ("Enter the 2nd Number:"))
def operator (O):
Dict_oper = {
' + ': 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)