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
{}
相关文章
相关标签/搜索