您的位置:首页 > 编程语言 > Python开发

Python中关于字典的操作

2013-12-19 16:22 579 查看
字典

python里的字典就像java里的HashMap,以键值对的方式存在并操作,其特点如下

通过键来存取,而非偏移量;
键值对是无序的;
键和值可以是任意对象;
长度可变,任意嵌套;
在字典里,不能再有序列操作,虽然字典在某些方面与列表类似,但不要把列表套在字典上

1) 基本操作

python 代码

>>> table = {'abc':1, 'def':2, 'ghi':3}

>>> table['abc']

1

>>> len(table)

3

>>> table.keys()

['abc', 'ghi', 'def']

>>> table.values()

[1, 3, 2]

>>> table.has_key('def')

True

>>> table.items()

[('abc', 1), ('ghi', 3), ('def', 2)]

2) 修改,删除,添加

python 代码

>>> table = {'abc':1, 'def':2, 'ghi':3}

>>> table['ghi'] = ('g', 'h', 'i')

>>> table

{'abc': 1, 'ghi': ('g', 'h', 'i'), 'def': 2}

>>> del table['abc']

>>> table

{'ghi': ('g', 'h', 'i'), 'def': 2}

>>> table['xyz'] = ['x', 'y', 'z']

>>> table

{'xyz': ['x', 'y', 'z'], 'ghi': ('g', 'h', 'i'), 'def': 2}

在这里需要来一句,对于字典的扩充,只需定义一个新的键值对即可,而对于列表,就只能用append方法或分片赋值。

3)对字典的遍历

python 代码

>>> table = {'abc':1, 'def':2, 'ghi':3}

>>> for key in table.keys():

print key, '/t', table[key]

abc 1

ghi 3

def 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: