python的字典

經常使用方法:python

最近有用到的 經過獲取對象中屬性纔用到spa

python獲取對象的屬性 vars(p) or p.__dict__ 返回的是屬性列表code

>>> class Point:
...     def __init__(self, x, y):
...             self.x = x
...             self.y = y
...
>>> p = Point(1,2)
>>> vars(p)
{'x': 1, 'y': 2}
>>> p.__dict__
{'x': 1, 'y': 2}

update 將2個字典合併orm

>>> s = {'a':9}
>>> s
{'a': 9}
>>> s.update(vars(p))
>>> s
{'a': 9, 'x': 1, 'y': 2}

字典取值(2種方法均可以取值,可是建議使用get,當去字典種不存在的值時使用第一種方法會報錯)對象

>>> s['a']
9
>>> s.get('a')
9

>>> s['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> s.get('c')
>>>blog

判斷是否存在某個鍵get

>>> 'a' in s
True

獲取全部的值,以及獲取全部的鍵,以及鍵值it

>>> s.values()
dict_values([9, 1, 2])
>>> s.keys()
dict_keys(['a', 'x', 'y'])
>>> s.items()
dict_items([('a', 9), ('x', 1), ('y', 2)])
>>> for k,v in s.items():
...     print('{}:{}'.format(k,v))
...
a:9
x:1
y:2

clear()清空字典裏面的數據ast

>>> s.clear()
>>> s
{}
相關文章
相關標籤/搜索