Python中的字典索引

Python中的符合数据类型:字符串,列表和序列。它们用整数作为索引。如果你试图用其他的类型做索引,就会产生错误。

>>> list = [1 ,2,3]
>>> list[0]
1
>>> list['one']
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    list['one']
TypeError: list indices must be integers, not str

字典的索引可以是字符串,除了这一点,它与其组合类型非常相似。当然,字典的索引也可以是整数。

>>> dict1 = {'mother':'妈妈','father','爸爸'}
SyntaxError: invalid syntax
>>> dict1 = {'mother':'妈妈','father':'爸爸'}
>>> dict1
{'father': '爸爸', 'mother': '妈妈'}
我们也可以创造一个空字典然后在添加元素。

>>> eng2sp = {}
>>> eng2sp['one'] = 'uno'
>>> eng2sp['two'] = 'dos'
>>> eng2sp
{'one': 'uno', 'two': 'dos'}

字典元素以逗号作为分隔符,每个元素包含键和键值,他们俩用冒号进行分割

字典的删除

>>> inventory = {'apples':430,'bananas':312,'oranges':525}
>>> inventory
{'bananas': 312, 'apples': 430, 'oranges': 525}
>>> del inventory['apples']
>>> inventory
{'bananas': 312, 'oranges': 525}

如果你想删除所有的元素,可以使用clear方法

>>> inventory.clear
<built-in method clear of dict object at 0x0000000003289588>
>>> inventory
{'bananas': 312, 'oranges': 525}
>>> inventory.clear()
>>> inventory
{}

使用函数len返回字典元素的数量

>>> os = {1:'Linux',2:'Windows'}
>>> len(os)
2

字典是可以改变的,如果你想修改字典,并且保留原来的备份,就要用到字典的copy方法,看看下面的例子:

>>> opp = {'up':'down','right':'left','true':'false'}
>>> alias = opp
>>> alias
{'right': 'left', 'up': 'down', 'true': 'false'}
>>> id(opp)
53056584
>>> id(alias)
53056584
>>> other = opp.copy()
>>> other
{'right': 'left', 'up': 'down', 'true': 'false'}
>>> id(other)
52898824




  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值