1. 程式人生 > >python dict 方法

python dict 方法

說字典方法之前,我們先來說幾個巧用字典取值的方法

1:

d = {'name':'zhang','age':25,'job':'IT'}

### 第一種方法
for key1in d:
   
print(key1,d[key1])

####  輸出結果
age 25
job IT
name zhang

2:

d = {'name':'zhang','age':25,'job':'IT'}

###  第二種方法
for k,v in d.items():
    print("dict[%s] = " %k,v)

###  輸出結果
dict[job] IT
dict[age] 25
dict[name] zhang

dict 類方法,不再細說

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)
    """

2:clear ---: 清空,返回空列表’{}’

def clear(self): # real signature unknown; restored from __doc__
    """ D.clear() -> None.  Remove all items from D. """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
d1 = d.clear()
print(d)

###  輸出結果
{}

3:copy ----: 淺拷貝

def copy(self): # real signature unknown; restored from __doc__
    """ D.copy() -> a shallow copy of D
"""    
pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
d1 = d.copy()
print(d1)

###  輸出結果
{'name': 'zhang', 'job': 'IT', 'age': 25}

4: fromkeys ---:建立並返回一個新字典,以seq中的元素做該字典的鍵,val做該字典中所有鍵對應的初始值

def fromkeys(*args, **kwargs): # real signature unknown
    """ Returns a new dict with keys from iterable and values equal to value. """
    pass

使用方法:

print(d1.fromkeys('name','zhang'))

###  輸出結果
{'n': 'zhang', 'm': 'zhang', 'a': 'zhang', 'e': 'zhang'}

5: get ---: 獲取值;對字典dict中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default值

def get(self, k, d=None): # real signature unknown; restored from __doc__
    """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
#d1 = {}
#print(d1.fromkeys('name','zhang'))
print(d.get('name'))
print(d.get('Height'))

###  輸出結果
zhang
None

6: items ---: 返回一個包含字典中鍵、值對元組的列表

def items(self): # real signature unknown; restored from __doc__
    """ D.items() -> a set-like object providing a view on D's items """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
print(d.items())

###  輸出結果
dict_items([('name', 'zhang'), ('job', 'IT'), ('age', 25)])

7: key ---: 返回所有的key

def keys(self): # real signature unknown; restored from __doc__
    """ D.keys() -> a set-like object providing a view on D's keys """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
print(d.keys())

###  輸出結果
dict_keys(['name', 'age', 'job'])

8:values ---: 返回所有的value

def values(self): # real signature unknown; restored from __doc__
    """ D.values() -> an object providing a view on D's values """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
print(d.values())

###  輸出結果
dict_values(['IT', 25, 'zhang'])

9: pop ---: 刪除指定的key,並返回相應的值,如果沒有此key,將報錯

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

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
d1 = d.pop('name')
print(d)
print(d1)

###  輸出結果
{'age': 25, 'job': 'IT'}
zhang

10: popitem --: 隨機刪除字典中的一對鍵值

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

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
print(d)
print(d.popitem())
print(d)

###  輸出結果
{'age': 25, 'name': 'zhang', 'job': 'IT'}
('age', 25)
{'name': 'zhang', 'job': 'IT'}

11: setdefault ---: 如果key 值存在則返回其值,如果不存在則新增此key ,預設以None作為其value

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
    """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
    pass

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
print(d.setdefault('name'))
d1 = d.setdefault(('Height'))
print(d)

###  輸出結果
zhang
{'name': 'zhang', 'job': 'IT', 'Height': None, 'age': 25}

12: update ---: 更新

def update(self, E=None, **F): # known special case of dict.update
    """
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then 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

使用方法:

d = {'name':'zhang','age':25,'job':'IT'}
d1 = {'Height':'170'}
d3 = d.update(d1)
print(d)

###  輸出結果
{'Height': '170', 'age': 25, 'name': 'zhang', 'job': 'IT'}

測試小程式

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

即: {'k1': 大於66 , 'k2':小於66}

心得:實現方法可能有很多,請吐槽

l = [11,22,33,44,55,66,77,88,99,90,]
d = {}
l1 = []
l2 = []

for i in l:
    if i > 66:
        l2 = l1.append(i)
        d1 = d.setdefault('key1',l1)
    if i < 66:
        l3 = l2.append(i)
        d1 = d.setdefault('key2',l2)
print(d)

####  輸出結果
{'key1': [77, 88, 99, 90], 'key2': [11, 22, 33, 44, 55]}