Python字典高級使用方法彙總

Python字典高級使用方法彙總

字典(dictionary)是python中的一種非常靈活和強大的數據結構,可以完成很多操作。本文總結了一些除了基本的初始化、賦值、取值之外的常用的字典使用方法。

字典基礎參考:
【1】:http://www.w3cschool.cc/python/python-dictionary.html
【2】:http://www.111cn.net/phper/python/56355.htm
【3】:http://skyfen.iteye.com/blog/567571
【4】:http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html

使用dict創建字典的n種方法

除了我們比較常用的d = {'a':1, 'b':2}來初始化字典外,還可以使用dict()來初始化,這種方法更爲靈活。以下介紹了用dict來初始化字典的幾種方法。

In [2]: dict?
Type:        type
String form: <type 'dict'>
Namespace:   Python builtin
Docstring:
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)

參數賦值

In [6]: d = dict(a=1,b=2)
In [7]: d
Out[7]: {'a': 1, 'b': 2}

用可迭代對象爲參數,且每一個迭代對象爲(k, v)

In [8]: l1 = ['a', 'b', 'c']
In [9]: l2 = [1, 2, 3]
In [11]: zip(l1,l2)
Out[11]: [('a', 1), ('b', 2), ('c', 3)]
In [12]: d = dict(zip(l1,l2))
In [13]: d
Out[13]: {'a': 1, 'b': 2, 'c': 3}

字典推導式(dictionary comprehension)

如同列表推導式,我們可以使用字典推導式來很簡潔的生成一些字典。

In [14]: d = { c:ord(c) for c in 'abc' }
In [15]: d
Out[15]: {'a': 97, 'b': 98, 'c': 99}

設置默認值

已經知道key的情況下批量生成默認值

如有一個列表l=['a', 'b', 'c'],要將其中的值作爲key,值全部設爲0。可以使用dict.fromkeys()來完成:

In [16]: d.fromkeys?
Type:        builtin_function_or_method
String form: <built-in method fromkeys of type object at 0x10017b9c0>
Docstring:
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.

示例代碼:

In [17]: l = ['a','b','c']
In [18]: d = {}
In [19]: d.fromkeys(l, 0)
Out[19]: {'a': 0, 'b': 0, 'c': 0}

若第二個參數不傳入則默認爲None

事先不知道會有哪些key

如要對一段字符文本s = 'hello, world!'進行字符統計,將結果保存在字典中。
由於事先不知道會有哪些key,因此在一個新的值傳入時,需要先判斷該值是否在字典中,若存在,則加1,否則置爲1。代碼如下:

d = {}
s = 'hello, world!'
for c in s:
    if c in d:
        d[c] += 1
    else:
        d[c] = 1

使用defaultdict

defaultdictcollections中提供的設置了默認值的字典類型。

In [20]: from collections import defaultdict
In [21]: s = 'hello, world!'
In [22]: d = defaultdict(int)
In [23]: for c in s: d[c] += 1
In [25]: d
Out[25]: defaultdict(<type 'int'>, {'!': 1, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'l': 3, 'o': 2, ',': 1, 'r': 1, 'w': 1})

使用setdefault方法來實現同時設置默認值和取值

dict自帶的setdefault方法,會在key存在時返回value,若不存在,則設爲指定值並返回這個值。如:

In [29]: d = {'a':1, 'b':2}
In [30]: d.setdefault('a', 3)
Out[30]: 1
In [31]: d.setdefault('c', 3)
Out[31]: 3
In [32]: d
Out[32]: {'a': 1, 'b': 2, 'c': 3}

用這個方法實現上述功能爲:

In [26]: d2 = {}
In [27]: for c in s: d2[c] = d2.setdefault(c, 0) + 1
In [28]: d2
Out[28]:
{' ': 1,
 '!': 1,
 ',': 1,
 'd': 1,
 'e': 1,
 'h': 1,
 'l': 3,
 'o': 2,
 'r': 1,
 'w': 1}

由此可見,在這種情況下,使用setdefault可以寫出和使用defaultdict方法同樣簡潔的代碼。

pop方法

python字典的pop方法會在鍵存在時返回該值,同時從字典中刪除該鍵,若不存在可以返回默認值。

In [33]: d
Out[33]: {'a': 1, 'b': 2, 'c': 3}
In [34]: d.pop('a')
Out[34]: 1
In [35]: d
Out[35]: {'b': 2, 'c': 3}
In [36]: d.pop('d')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-36-ee5e0ecd6e46> in <module>()
----> 1 d.pop('d')

KeyError: 'd'

In [37]: d.pop('d', 0)
Out[37]: 0

這個在我們需要判斷一個特殊的字典並進行處理的時候非常有用。
假定我們有一個處理字典的函數:

def process_dict(d):
   dosomething(d)

它接收所有人的字典並進行處理。假定現在你傳入的字典需要進行一些其他的特殊處理,如何讓函數識別傳入的是你的字典並且不產生副作用呢?
我們可以將函數改爲:

def process_dict(d):
    if d.pop('is_mine', False):
        do_something_special(d)
    dosomething(d)

然後對於你要傳入的字典設定k['is_mine']=True再傳入該函數,進入函數後pop方法會將其彈出,識別出這是你的,進行一些操作,再繼續。對於不存在該key的字典來說,返回False,不產生任何副作用。

遍歷字典的n種方法

  1. d.keys(),d.values(),d.items()分別返回鍵,值,鍵值對的列表。
     In [38]: d
     Out[38]: {'b': 2, 'c': 3}
     In [39]: d.keys()
     Out[39]: ['c', 'b']
     In [40]: d.values()
     Out[40]: [3, 2]
     In [41]: d.items()
     Out[41]: [('c', 3), ('b', 2)]
    
  2. d.iterkeys(),d.itervalues(),d.iteritems()分別返回鍵,值,鍵值對的迭代對象。如果你只是想要遍歷的話,建議使用這個。因爲它不是一次生成所有對象,而是用一個生成一個,無論在速度還是內存佔用上都有優勢。

     In [42]: d.iterkeys()
     Out[42]: <dictionary-keyiterator at 0x103858578>
    
     In [43]: list(d.iterkeys())
     Out[43]: ['c', 'b']
    
  3. d.viewkeys(),d.viewvalues(),d.viewitems()返回一個類似set的對象,其特點是會隨着d的變化而動態變化。
    In [48]: d
    Out[48]: {'a': 1, 'b': 2, 'c': 3}
    In [49]: keys = d.keys()
    In [50]: viewkeys = d.viewkeys()
    In [52]: del d['a']
    In [53]: d
    Out[53]: {'b': 2, 'c': 3}
    In [54]: keys
    Out[54]: ['a', 'c', 'b']
    In [55]: viewkeys
    Out[55]: dict_keys(['c', 'b'])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章