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
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
相关文章推荐
- Python实用技巧-成为Pythoner必经之路
- Windows下安装MySQL-python
- Python脚本控制的WebDriver 常用操作 <二十六> 上传文件
- python的super用法遇到的问题
- python 操作excel2007
- 测试网页是否能正常登陆
- Maven_Python打包遇到的问题总结
- 用python开发调试器——起始篇
- python 正则表达式
- Python 3.2: 使用pymysql连接Mysql
- python 中的 filter, lambda, map, reduce 内置函数
- 经典排序算法python回顾之二 选择排序
- python的vim的简单设置
- Python中%s和%r的区别
- 【转】The Zen of Python
- 【记录】Python中安装xlrd模块
- Python学习笔记(五),条件,循环和其它语句(下)
- Python快速教程
- 服务端socket开发之多线程和gevent框架并发测试[python语言] 推荐
- Python 3 智能发音