2021-08-21

Python中获取字典值get()和items()

1.get()

当我们获取字典里的值的时候,一个是通过键值对,即dict[‘key’],另一个就是dict.get()方法。

例如:


>>> dict = {'a':'AA', 'b':'BB', 'c':'CC'}
>>> dict['a']
'AA'
>>> dict.get('a')
'AA'

get()方法语法:
dict.get(key, default=None)
key – 字典中要查找的键。
default – 如果指定键的值不存在时,返回该默认值。
例如:

>>> dict.get('d','error')
'error'

2.iteritems(),python3中已经废除直接用items()
python字典中还存在items()方法。两者有些许区别。

items方法是可以将字典中的所有项,以列表方式返回。
iteritems方法与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器。

d = {'1':'one', '2':'two', '3':'three'}
x = d.items()
x
Out[4]: dict_items([('1', 'one'), ('2', 'two'), ('3', 'three')])
type(x)
Out[5]: dict_items
for i in x:
    print(i)
    
('1', 'one')
('2', 'two')
('3', 'three')

3.dict

class A(object):
    class_var = 1
    def __init__(self):
        self.name = 'xy'
        self.age = 2

    @property
    def num(self):
        return self.age + 10

    def fun(self):pass
    def static_f():pass
    def class_f(cls):pass

if __name__ == '__main__':#主程序
    a = A()
    print (a.__dict__)   #{'age': 2, 'name': 'xy'}   实例中的__dict__属性
    print (A.__dict__  ) 
    '''
    类A的__dict__属性
    {
    '__dict__': <attribute '__dict__' of 'A' objects>, #这里如果想深究的话查看参考链接5
    '__module__': '__main__',               #所处模块
    'num': <property object>,               #特性对象 
    'class_f': <function class_f>,          #类方法
    'static_f': <function static_f>,        #静态方法
    'class_var': 1, 'fun': <function fun >, #类变量
    '__weakref__': <attribute '__weakref__' of 'A' objects>, 
    '__doc__': None,                        #class说明字符串
    '__init__': <function __init__ at 0x0000000003451AC8>}
    '''

    a.level1 = 3
    a.fun = lambda :x
    print (a.__dict__)  #{'level1': 3, 'age': 2, 'name': 'xy','fun': <function <lambda> at 0x>}
    print (A.__dict__ ) #与上述结果相同

    A.level2 = 4
    print (a.__dict__)  #{'level1': 3, 'age': 2, 'name': 'xy'}
    print (A.__dict__ ) #增加了level2属性

    print (object.__dict__)
    '''
    {'__setattr__': <slot wrapper '__setattr__' of 'object' objects>, 
    '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>, 
    '__new__': <built-in method __new__ of type object at>, 
    等.....
从上述代码可知,

实例的__dict__仅存储与该实例相关的实例属性,

正是因为实例的__dict__属性,每个实例的实例属性才会互不影响。

类的__dict__存储所有实例共享的变量和函数(类属性,方法等),类的__dict__并不包含其父类的属性。'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值