现在的位置: 首页 > 综合 > 正文

Python中的字典索引

2017年12月15日 ⁄ 综合 ⁄ 共 1238字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.