Python中字典建立、遍曆、添加等實用操作技巧合集

來源:互聯網
上載者:User
欄位是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)

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.