常用方法:

最近有用到的 通过获取对象中属性才用到

python获取对象的属性 vars(p) or p.__dict__ 返回的是属性列表

>>> 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个字典合并

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

判断是否存在某个键

>>> 'a' in s
True

获取所有的值,以及获取所有的键,以及键值

>>> 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()清空字典里面的数据

>>> s.clear()
>>> s
{}

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!