Python核心数据类型之字典类型及其运算

Python核心数据类型之字典类型及其运算

字典:dict

字典在其它编程语言中又称作关联数组或散列表;通过键实现元素存取;是无序集合;可变类型容器,长度可变,支持异构和嵌套;

格式:{key1:value1, key2:value2, ...}

{}: 空字典

{'x': 32, 'y': [1,2,3]}

字典复制:

d2 = d1.copy()

d3 = d1

字典内置方法:

d1.clear():清除字典中所有项目      

d1.has_key(k):是否存在某键k    

d1.itervalues():返回一个值的迭代器对象,i1= d1.itervalues(),可使用i1.next()查看各个对象 

d1.viewkeys():以集合的方式显示所有键

d1.copy():返回d1的一个副本,id会改变       

d1.items():返回由(key,value)组成的一个序列

d1.keys():返回字典中的键       

d1.update(d2):将d2中所有对象添加到d1中     

d1.viewvalues():以集合的方式显示所有值

d1.fromkeys(s [,value]):创建一个新字典并将序列s中的所有元素作为新字典的键,且这些键的值均为value,value无设定是值为None   

d1.iteritems():返回一个迭代器对象,i1= d1.iteritems(),可使用i1.next()查看各个对象

d1.pop():弹出一个对象        

d1.values():返回d1的所有值     

d1.get(x):获取d1中键x的值

d1.iterkeys():返回一个键的迭代器对象,i1 =d1.iterkeys(),可使用i1.next()查看各个对象 

d1.popitem():弹出d1的一个项目    

d1.viewitems:以集合的方式显示所有键值(元组)  

例1:字典创建及支持操作(索引、切片)示例

In [26]: d1 = {'x':12,'y':[1,2,3,4]}

In [27]: print d1

{'y': [1, 2, 3, 4], 'x': 12}

In [28]: d1['x']

Out[28]: 12

In [29]: d1['y']

Out[29]: [1, 2, 3, 4]

In [30]: d1['y'][2:]

Out[30]: [3, 4]

In [31]: len(d1)

Out[31]: 2

In [32]: d1['x'] = 666

In [33]: print d1

{'y': [1, 2, 3, 4], 'x': 666}

例2:字典内置方法的使用

In [34]: d1.

d1.clear       d1.has_key     d1.itervalues  d1.setdefault d1.viewkeys

d1.copy        d1.items       d1.keys        d1.update      d1.viewvalues

d1.fromkeys    d1.iteritems   d1.pop         d1.values     

d1.get         d1.iterkeys    d1.popitem     d1.viewitems  

In [34]: d2 = d1.copy()

In [35]: d3 = d1

In [36]: print d3

{'y': [1, 2, 3, 4], 'x': 666}

In [37]: print d2

{'y': [1, 2, 3, 4], 'x': 666}

In [38]: id(d1)

Out[38]: 32351168

In [39]: id(d2)

Out[39]: 32176688

In [40]: id(d3)

Out[40]: 32351168

In [41]: d1.get('x')

Out[41]: 666

In [42]: d1.get('y')

Out[42]: [1, 2, 3, 4]

In [43]: d1.get('z')

In [44]: d1.has_key('x')

Out[44]: True

In [45]: d1.has_key('z')

Out[45]: False

In [46]: d1.ite

d1.items       d1.iteritems   d1.iterkeys    d1.itervalues 

In [46]: d1.items()

Out[46]: [('y', [1, 2, 3, 4]), ('x', 666)]

In [47]: t1, t2 = d1.items()

In [48]: print t1

('y', [1, 2, 3, 4])

In [49]: print t2

('x', 666)

In [50]: d1.keys()

Out[50]: ['y', 'x']

In [51]: d1.values()

Out[51]: [[1, 2, 3, 4], 666]

In [52]: d1.pop('x')

Out[52]: 666

In [53]: print d1

{'y': [1, 2, 3, 4]}

例3:字典内置迭代器的使用

In [56]: d2 = {'x':1,'y':2,'z':3}

In [57]: d2.popitem()

Out[57]: ('y', 2)

In [58]: d2.popitem()

Out[58]: ('x', 1)

In [59]: d2.popitem()

Out[59]: ('z', 3)

In [60]: d2.popitem()

---------------------------------------------------------------------------

KeyError                                  Traceback(most recent call last)

<ipython-input-60-964b229ff779> in<module>()

----> 1 d2.popitem()

KeyError: 'popitem(): dictionary is empty'

#字典元素全部弹出,内容为空时继续使用popitem()方法会报KeyError(值错误)

In [61]: d1 = {'x':1,'y':2}

In [63]: d2 = {'y':666,'z':33,'m':55}

In [64]: d1.update(d2)

In [65]: print d1

{'y': 666, 'x': 1, 'z': 33, 'm': 55}

In [66]: i1 = d1.iteritems()

In [67]: i1.next()

Out[67]: ('y', 666)

In [68]: i1.next()

Out[68]: ('x', 1)

In [69]: i1.next()

Out[69]: ('z', 33)

In [70]: i1.next()

Out[70]: ('m', 55)

In [71]: i1.next()

---------------------------------------------------------------------------

StopIteration                             Traceback (mostrecent call last)

<ipython-input-71-be7912f76fe0> in<module>()

----> 1 i1.next()

StopIteration:

# iteritems()方法返回的迭代器对象,在使用i1.next()方法逐一查看完成后会返回StopIteration

In [72]: i2 = d1.iterkeys()

In [73]: i2.next()

Out[73]: 'y'

In [74]: i2.next()

Out[74]: 'x'

In [75]: i2.next()

Out[75]: 'z'

In [76]: i2.next()

Out[76]: 'm'

In [77]: i2.next()

---------------------------------------------------------------------------

StopIteration                             Traceback (mostrecent call last)

<ipython-input-77-26e3ebe37329> in<module>()

----> 1 i2.next()

StopIteration:

# iterkeys()方法返回的迭代器对象,在使用i1.next()方法逐一查看完成后会返回StopIteration

In [78]: i3 = d1.itervalues()

In [79]: i3.next()

Out[79]: 666

In [80]: i3.next()

Out[80]: 1

In [81]: i3.next()

Out[81]: 33

In [82]: i3.next()

Out[82]: 55

In [83]: i3.next()

---------------------------------------------------------------------------

StopIteration                             Traceback (mostrecent call last)

<ipython-input-83-a0267d328718> in<module>()

----> 1 i3.next()

StopIteration:

# itervalues()方法返回的迭代器对象,在使用i1.next()方法逐一查看完成后会返回StopIteration

例:4:集合的方式显示所有键值(元组)

In [84]: d1.viewitems()

Out[84]: dict_items([('y', 666), ('x', 1),('z', 33), ('m', 55)])

例5:集合的方式显示所有键

In [86]: d1.viewkeys()

Out[86]: dict_keys(['y', 'x', 'z', 'm'])

例6:集合的方式显示所有值

In [87]: d1.viewvalues()

Out[87]: dict_values([666, 1, 33, 55])

例7:字典创建

In [88]: d2 =dict(name='Jones',age=30,gender='M')

In [89]: print d2

{'gender': 'M', 'age': 30, 'name': 'Jones'}

例8:使用zip方法构建元素为元组的列表

In [91]: zip('xyz','123')

Out[91]: [('x', '1'), ('y', '2'), ('z','3')]

In [92]: zip('xyz','1234')

Out[92]: [('x', '1'), ('y', '2'), ('z','3')]

In [93]: zip('xyzm','564')

Out[93]: [('x', '5'), ('y', '6'), ('z','4')]

In [94]: zip('xyz','123','abc')

Out[94]: [('x', '1', 'a'), ('y', '2', 'b'),('z', '3', 'c')]

例9:使用dict(zip())快速构建字典

In [95]: dict(zip('xyz','123'))

Out[95]: {'x': '1', 'y': '2', 'z': '3'}

例10:使用某序列中对象作为字典键并赋同一个值

In [104]: s1=['x','y','z','m']

In [105]: d1.fromkeys(s1,20)

Out[105]: {'m': 20, 'x': 20, 'y': 20, 'z':20}

In [106]: d1.fromkeys(s1)

Out[106]: {'m': None, 'x': None, 'y': None,'z': None}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值