字段是Python是字典中唯一的鍵-值類型,是Python中非常重要的數據結構,因其用哈希的方式存儲數據,其復雜度為O(1),速度非常快。下面列出字典的常用的用途.
一、字典中常見方法列表
#方法????????????????????????????????? #描述?
-------------------------------------------------------------------------------------------------?
D.clear()????????????????????????????? #移除D中的所有項?
D.copy()?????????????????????????????? #返回D的副本?
D.fromkeys(seq[,val])????????????????? #返回從seq中獲得的鍵和被設置為val的值的字典。可做類方法調用?
D.get(key[,default])?????????????????? #如果D[key]存在,將其返回;否則返回給定的默認值None?
D.has_key(key)???????????????????????? #檢查D是否有給定鍵key?
D.items()????????????????????????????? #返回表示D項的(鍵,值)對列表?
D.iteritems()????????????????????????? #從D.items()返回的(鍵,值)對中返回一個可迭代的對象?
D.iterkeys()?????????????????????????? #從D的鍵中返回一個可迭代對象?
D.itervalues()???????????????????????? #從D的值中返回一個可迭代對象?
D.keys()?????????????????????????????? #返回D鍵的列表?
D.pop(key[,d])???????????????????????? #移除并且返回對應給定鍵key或給定的默認值D的值?
D.popitem()??????????????????????????? #從D中移除任意一項,并將其作為(鍵,值)對返回?
D.setdefault(key[,default])??????????? #如果D[key]存在則將其返回;否則返回默認值None?
D.update(other)??????????????????????? #將other中的每一項加入到D中。?
D.values()???????????????????????????? #返回D中值的列表
二、創建字典的五種方法
方法一: 常規方法???
# 如果事先能拼出整個字典,則此方法比較方便
>>> D1 = {'name':'Bob','age':40}?
方法二: 動態創建
# 如果需要動態地建立字典的一個字段,則此方法比較方便
>>> D2 = {}?
>>> D2['name'] = 'Bob'?
>>> D2['age']? =? 40?
>>> D2?
{'age': 40, 'name': 'Bob'}
方法三:? dict--關鍵字形式??????
# 代碼比較少,但鍵必須為字符串型。常用于函數賦值
>>> D3 = dict(name='Bob',age=45)?
>>> D3?
{'age': 45, 'name': 'Bob'}
方法四: dict--鍵值序列
# 如果需要將鍵值逐步建成序列,則此方式比較有用,常與zip函數一起使用
>>> D4 = dict([('name','Bob'),('age',40)])?
>>> D4?
{'age': 40, 'name': 'Bob'}
或
>>> D = dict(zip(('name','bob'),('age',40)))?
>>> D?
{'bob': 40, 'name': 'age'}?
方法五: dict--fromkeys方法# 如果鍵的值都相同的話,用這種方式比較好,并可以用fromkeys來初始化
>>> D5 = dict.fromkeys(['A','B'],0)?
>>> D5?
{'A': 0, 'B': 0}?
如果鍵的值沒提供的話,默認為None
>>> D3 = dict.fromkeys(['A','B'])?
>>> D3?
{'A': None, 'B': None}?
三、字典中鍵值遍歷方法
>>> D = {'x':1, 'y':2, 'z':3}????????? # 方法一?
>>> for key in D:?
??? print key, '=>', D[key]???
y => 2?
x => 1?
z => 3?
>>> for key, value in D.items():?????? # 方法二?
??? print key, '=>', value????
y => 2?
x => 1?
z => 3?
?
>>> for key in D.iterkeys():?????????? # 方法三?
??? print key, '=>', D[key]???
y => 2?
x => 1?
z => 3?
>>> for value in D.values():?????????? # 方法四?
??? print value??
2?
1?
3?
>>> for key, value in D.iteritems():?? # 方法五?
??? print key, '=>', value?
?????
y => 2?
x => 1?
z => 3?
Note:用D.iteritems(), D.iterkeys()的方法要比沒有iter的快的多。
四、字典的常用用途之一代替switch
在C/C++/Java語言中,有個很方便的函數switch,比如:
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");?
??????? }?
??? }?
}?
在Python中要實現同樣的功能,
方法一,就是用if, else語句來實現,比如:
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)?
方法二,用字典來巧妙實現同樣的switch的功能,比如:
#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)?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
