Python中的符合数据类型:字符串,列表和序列。它们用整数作为索引。如果你试图用其他的类型做索引,就会产生错误。
>>> list = [1 ,2,3]
>>> list[0]
1
>>> list['one']
Traceback (most recent call last):
File "", line 1, in
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}
>>> inventory.clear
>>> inventory
{'bananas': 312, 'oranges': 525}
>>> inventory.clear()
>>> inventory
{}
>>> 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