Python入门教程-10 字典dictionary

定义方法、遍历keys、取某个key的值、修改value。

>>> d = {'name':'Tom', 'age':5}
>>> type(d)
<type 'dict'>
>>> d.keys()
['age', 'name']
>>> for key in d:
...     print key, ":", d[key]
... 
age : 5
name : Tom
>>> d.has_key('name')
True
>>> d.has_key('xyz')
False
>>> d['age']=6
>>> d
{'age': 6, 'name': 'Tom'}
>>> 



要点:

  • items(): 获取所有元素
  • keys(): 获取所有的key
  • [key]: 取key对应的值
  • has_key(key): 判断是否有某个值

>>> values={}
>>> values['one']='1 x 1 = 1'
>>> values['two']='2 x 2 = 4'
>>> values['three'] = '3 x 3 = 9'
>>> values.items()
[('three', '3 x 3 = 9'), ('two', '2 x 2 = 4'), ('one', '1 x 1 = 1')]
>>> values.keys()
['three', 'two', 'one']
>>> values['two']
'2 x 2 = 4'
>>> values['four']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'four'
>>> values.has_key('four')
False
>>> for the_key, the_value in values.items():
...     print "%s ==> %s" % (the_key, the_value)
... 
three ==> 3 x 3 = 9
two ==> 2 x 2 = 4
one ==> 1 x 1 = 1
>>> 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值