1. 程式人生 > >Python 字典

Python 字典

pre this 叠代 closed .get raise 清除 found python

1、創建一個字典

>>> a = {name: gm, age: 18}
>>> a
{age: 18, name: gm}

2、查看字典

# 獲取字典a的值
>>> a
{age: 18, name: gm}

# 獲取特定key的值
>>> a.[‘name‘]gm
>>> a.[‘age‘]18

3、查看字典可以進行的操作

>>> dir(a)
[__class__, __contains__, __delattr__
, __delitem__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __gt__, __hash__, __init__, __iter__, __le__, __len__, __lt__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __setitem__, __sizeof__, __str__
, __subclasshook__, clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, values]

技術分享
class dict(object):
    """
    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)
    
""" def clear(self): # real signature unknown; restored from __doc__ """ 清除內容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 淺拷貝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根據key獲取值,d是默認值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有項的列表形式 """ """ D.items() -> list of D‘s (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 項可叠代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可叠代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可叠代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D‘s keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 獲取並在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 獲取並在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,則創建,如果存在,則返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {‘name‘:‘alex‘, ‘age‘: 18000} [(‘name‘,‘sbsbsb‘),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D‘s values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有項,只是將內容保存至view對象中 """ """ D.viewitems() -> a set-like object providing a view on D‘s items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D‘s keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D‘s values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__(‘name‘) <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ 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) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None
dict

4、常用的字典操作

# 插入新的鍵值
>>> a {age: 18, name: gm} >>> a[job] = 運維 >>> a {age: 18, job: 運維, name: gm}

# 修改字典某鍵的值

>>> a
{age: 18, name: gm}
>>> a[name]=root
>>> a
{age: 18, name: root}

# 如何獲取字典某元素的值
>>> a
{age: 18, job: 運維, name: gm}
>>> a[gender] Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> a[gender] KeyError: gender

>>> a.get(gender) >>> a.get(gender,-1) -1
>>> a.get(name,-1) gm

# 刪除字典某元素

>>> a
{age: 18, job: 運維, name: gm}

>>> a.pop(job)
運維
>>> a
{age: 18, name: gm}

# 獲取字典刪除的元素的值
>>> a {age: 18, job: 運維, name: gm} >>> c = a.pop(job) >>> c 運維 >>> a {age: 18, name: gm}

# Python3中字典的keys()、values()、items()方法的區別

>>> a.keys()       # 以列表返回字典所有的鍵
dict_keys([age, job, name])

>>> a.values()     # 以列表返回字典中的所有值
dict_values([18, 運維, gm])

>>> a.items()      # 以列表返回字典可遍歷的(鍵, 值) 元組數組
dict_items([(age, 18), (job, 運維), (name, gm)])

5、字典練習

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],
將所有大於 66 的值保存至字典的第一個key中,
將小於 66 的值保存至第二個key的值中。
即: {k1: 大於66 , k2: 小於66}

  

b = {}
a = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90, ]

for i in a:
    if i > 66:
        if k1 in b.keys():
            b[k1].append(i)
        else:
            b[k1]= [i, ]
    else:
        if k2 in b.keys():
            b[k2].append(i)
        else:
            b[k2]= [i, ]

print(b[k1])
print(b[k2])

Python 字典